Git Product home page Git Product logo

json_serializable.dart's Introduction

Dart CI

Provides Dart Build System builders for handling JSON.

json_serializable Pub Package

The core package providing Generators for JSON-specific tasks.

Import it into your pubspec dev_dependencies: section.

json_annotation Pub Package

The annotation package which has no dependencies.

Import it into your pubspec dependencies: section.

checked_yaml Pub Package

Generate more helpful exceptions when decoding YAML documents using package:json_serializable and package:yaml.

Import it into your pubspec dependencies: section.

example

An example showing how to set up and use json_serializable and json_annotation.

json_serializable.dart's People

Contributors

ascenio avatar chalin avatar chresyr avatar dependabot[bot] avatar feinstein avatar fzyzcjy avatar jaicewizard avatar jakemac53 avatar johnpryan avatar jonasfj avatar jpelgrim avatar kevmoo avatar lassazvegaz avatar lejard-h avatar lynn avatar misterjimson avatar natebosch avatar pdf avatar rrousselgit avatar sasha-caleo avatar scheglov avatar serena867 avatar slightfoot avatar ssabdb avatar sunlightbro avatar tatsuyafujisaki avatar toureholder avatar tvolkert avatar vanlooverenkoen avatar zbarbuto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

json_serializable.dart's Issues

Add casting support

I've integrated with a very bad API. Their JSON didn't have any types, it was all strings. It would be very usefull to have something like this:

{
  "ugly": "true",
}
@JsonSerializable()
class Example {
  Example({this.pretty});

  @JsonKey(
    name: 'ugly',
    fromJson: (v) => v == 'true',
    toJson: (v) => v.toString(),
  )
  final bool pretty;
}

How do I deserialize a JSONArray?

Whats the best way to do this? The solution I found right now is pretty crappy?

 http.Response resp = await http.get('$endpoint');
List l = json.decode(resp.body);
    List<Message> c = new List();
    l.forEach((i){
      c.add(new Message.fromJson(i));
      return i;
    });

    return c;

More than one field has the JSON key `item`.

Unsure if this is a new feature or just a case of not understanding how to use it correctly.

I use xml2json to convert an xml into Google Data json. A 'section' has one or more 'item' children. If there is only one, it becomes an Object property. If there are multiple, an Array.

Currently I have: @jsonkey(name: "item", nullable: true)
final List items;

But it throws an error when encountering an item Object.

Is there any way to ensure that a single Item Object will get serialized into a , or is there another way of handling this?

Don't serialize/deserialize private fields especially when they are encapsulated

As descriped in #74 I can't change the fact that my bool are overwritten by null, because the field isn't in the json. My thought was, that I need to encapsulate the field then to correct the values.

  bool _myBool = false;

  bool get myBool => _myBool;

  void set myBool(bool value) {
    if (value != null)
      _myBool = value;
  }

It doesn't help either, as now both the private and public members are deserialized:

GeneralConfiguration _$GeneralConfigurationFromJson(
        Map<String, dynamic> json) =>
    new GeneralConfiguration()
      .._myBool = json['_myBool'] as bool
      ..myBool = json['myBool'] as bool

Serializing member objects

In the example.dart file, class Person has a List of Orders with both classes annotated as serializable.
However the member List doesn't get serialized in Person.toJson(), is that intentional?

Map<String, dynamic> toJson() {
    var val = <String, dynamic>{
      'firstName': firstName,
    };

    void writeNotNull(String key, dynamic value) {
      if (value != null) {
        val[key] = value;
      }
    }

    writeNotNull('middleName', middleName);
    val['lastName'] = lastName;
    val['date-of-birth'] = dateOfBirth.toIso8601String();
    val['last-order'] = lastOrder?.toIso8601String();
    val['orders'] = orders; // <-- Shouldn't this be: val['orders'] = orders.toJson(); 
    return val;
  }

Requesting more prescriptive README for example w.r.t. script

The README in the example says "create the scripts to run code generation", but I don't know how to take action on that. Can we be more prescriptive? I know you link to the tool/ directory but can you be more specific?

What's the MVP step-by-step I need to do in order to use this? Cut-n-paste style :)

For example, do I need all three of the scripts you mention? Do I pick one to start? Do I just copy and paste these three scripts into my app? Where would I paste these script into?

Not clear how to use this (these?) packages

These packages seem great, but it's not clear how to use them? Neither the repo nor the two package READMEs provide step-by-step instructions. They seem to assume that I know things I probably don't :)

Would love to share these with Flutter ecosystem, but would like first to point people to usage instructions.

Thanks!

flutter packages pub run build_runner build fail

#0 _Loader._initialBuildCleanup (package:build_runner/src/generate/build_definition.dart:422:9)

#1 _Loader.prepareWorkspace. (package:build_runner/src/generate/build_definition.dart:130:17)
#2 logTimedAsync (package:build_runner/src/logging/logging.dart:26:30)

#3 _Loader.prepareWorkspace (package:build_runner/src/generate/build_definition.dart:127:13)

#4 BuildDefinition.prepareWorkspace (package:build_runner/src/generate/build_definition.dart:65:12)
#5 WatchImpl._run. (package:build_runner/src/generate/watch_impl.dart:264:48)

#6 WatchImpl._run (package:build_runner/src/generate/watch_impl.dart:283:6)
#7 new WatchImpl (package:build_runner/src/generate/watch_impl.dart:160:9)
#8 runWatch (package:build_runner/src/generate/watch_impl.dart:115:9)
#9 watch (package:build_runner/src/generate/watch_impl.dart:94:7)

#10 watch (package:build_runner/src/generate/build.dart:124:5)
#11 _WatchCommand.run (package:build_runner/src/entrypoint/options.dart:298:25)

#12 CommandRunner.runCommand (package:args/command_runner.dart:194:27)

#13 CommandRunner.run. (package:args/command_runner.dart:109:29)
#14 new Future.sync (dart:async/future.dart:224)
#15 CommandRunner.run (package:args/command_runner.dart:109:11)
#16 run (package:build_runner/src/entrypoint/run.dart:15:24)

#17 main (file:///Users/cjl/IdeaProjects/flutter/flutter-wanandroid/.dart_tool/build/entrypoint/build.dart:12:22)

#18 _startIsolate. (dart:isolate-patch/dart:isolate/isolate_patch.dart:275)
#19 _RawReceivePortImpl._handleMessage (dart:isolate-patch/dart:isolate/isolate_patch.dart:165)
pub finished with exit code 1


When I run the 'flutter packages pub run build_runner watch' or 'flutter packages pub run build_runner build', I get the error with my commend line.


I use the json_serializable: "^0.5.0"

Not clear if this is an officially supported package?

Is this an experiment? Supported by Dart? the way to do JSON? Should Flutter users use this?

Can we be more clear about what this is, in the README?

(a lot of people are excited for better JSON, I want to clearly set expectations if possible. Thanks!)

Annotations do not support enums and user defined constant objects

From @ds84182 on February 28, 2016 18:13

For example, lets say you wanted to extend the JSON serializer to support value validation:

Something like this works just fine:

@JsonSerializable()
class ProtocolHandshake extends Object with _$ProtocolHandshakeMixin {
  @Equals(47) 
  final int version;
  //...
}

But something like this does not:

@JsonSerializable()
class ProtocolEntityData extends Object with _$ProtocolEntityDataMixin {
  @KeyValidator(const TypeValidator(String))
  @ValueValidator(const TypeValidator(String))
  Map<String, String> data;
}

Or something using enums like this:

enum Side {
  SERVER,
  CLIENT
}

@PacketDef(target: Side.CLIENT)
class ProtocolIntList extends Object with _$ProtocolIntListMixin {
  //...
}

Copied from original issue: dart-lang/source_gen#78

Consider supporting `Set`s in constructors

Consider a class like:

class MyThing {
  final Set<int> myInts;

  MyThing(this.myInts);
}

Today the generated fromJson constructor would end up trying to pass in an Iterable<int> to the constructor, which won't work. The workaround is:

class MyThing {
  final Set<int> myInts;

  MyThing(Iterable<int> myInts) : this.myInts = myInts.toSet();
}

...but ideally that wouldn't be necessary :).

fwiw, for List fields it will automatically call toList on the iterable before passing it in.

Git warnings about "LF" being replaced by "CRLF" on windows

After building when commiting files I consistently get these warnings for each generated file. This might be a source_gen issue?

warning: LF will be replaced by CRLF in lib/some_path.g.dart.
The file will have its original line endings in your working directory.

Doing too much with type Map<String, [jsonType]>

I messed something up

-PkgDeps _$PkgDepsFromJson(Map json) =>
-    new PkgDeps(json['deps'] as Map<String, String>);
+PkgDeps _$PkgDepsFromJson(Map json) => new PkgDeps(json['deps'] == null
+    ? null
+    : new Map<String, String>.fromIterables((json['deps'] as Map).keys,
+        (json['deps'] as Map).values.map((v0) => v0 as String)));

Add annotation to ignore a field

It would be useful (at least for me) to have an annotation to ignore the serialization of certain fields.

@JsonSerializable()
Class Person {

@jsonkey(ignore: true)
final bool isNew;

}

Document all options

  • Document that generic classes (with generic fields) will likely only work if they use to/from Json

Split package on generator and annotations

Hello.
Thanks for awesome package for json stuff.
At our project we separate all analyzer, source_gen deps to separate project and use them as cli. This helps migrate on new versions of sdk withour worrying and resolve dependency conflicts between transitive deps.

Is it possible to split this package on generator and annotations? So forth we can depend at our code directly from annotations and all analyzer stuff will be isolated in another package.

Serialization of nested serializable objects

Looks like serializing of annotated object with nested annotated objects via toJson() are not supported or I am completely don't understand how to do it.

Calling method toJson() even for your Person object (which is in your example along with nested Order and Item, code unchanged) fails to include serialized output of nested objects into final output.

Order order1 = new Order()
  ..count = 2
  ..itemNumber = 1
  ..isRushed = true
  ..item = new Item()
  ..itemNumber = 234
  ..isRushed=false;

Person person = new Person('Alexey', 'Kartavenko', new DateTime.now(), orders: <Order>[order1]);
print(person.toJson());

Result:

{firstName: Alexey, lastName: Kartavenko, date-of-birth: 2017-10-07T15:15:11.616592, last-order: null, orders: [Instance of 'Order']}

Looking into generated model code I don't see any attempts to call toJson() method of Order object. Is this by design or am I missing something obvious here?

inheritance support

Is inheritance supported? I've tried the following example but got an exception, is there something i miss?:

@JsonSerializable()
abstract class Base extends Object with _$BaseSerializerMixin {
  Base(this.value);

  num value;

  factory Base.fromJson(Map<String, dynamic> json) => _$BaseFromJson(json);
}

@JsonSerializable()
class Sub extends Base with _$SubSerializerMixin {
  Sub(num value, this.subVal): super(value);

  num subVal;

  factory Sub.fromJson(Map<String, dynamic> json) => _$SubFromJson(json);
}

exception thrown:

Unsupported operation: Cannot populate the required constructor argument: value.

Support an option to not allow explicit null values for nullable fields.

See InputSet as an example. Both of its fields are allowed to be null, but we don't really want users to be able to specify them as null explicitly in yaml. For instance, this should give an error:

targets:
  $default:
    sources:
      include:

include: there isn't treated any differently than if it didn't exist at all, and should probably be an error.

Add option to omit null fields in fromJson constructor or define default values

Great Library. Finally something to replace Dartson with. However: When deserializing fields that aren't in the json, they will be written to the object as null. In Angular I then get errors like "boolean expression must not be null". I would like to keep the default values assigned to the fields instead of having those overwritten by null:

// Please keep my assigned value, don't overwrite with null
bool myBool = true

Or maybe setting the default value with an annotation would be useful.

@JsonKey(default: true)
bool myBool

Add an option to throw on extra keys during deserialization

Specifically for the yaml use case, but really whenever json is coming from hand written code, it is important to be able to give an error about unused keys.

This helps people realize common typo and other mistakes in their yaml files.

Handle potentially aliased imports

It's really not safe to reference Map or String in the case where someone does import "dart:core" as foo; – in practice this should be rare.

Same for other types. In general, we just write out the type name w/ out worrying about imports.

Support custom DateTime formats

I'd like to (un)serialize a DateTime in a custom format, such as:

 new DateFormat('M/d/yyyy');

Currently I get a runtime exception:

I/flutter (20794): FormatException: Invalid date format
I/flutter (20794): 04/10/2015

Handle missing constructor more cleanly

From @kevmoo on March 3, 2016 22:2

Input

@JsonSerializable()
class TestDoneEvent extends Object
    with _$TestDoneEventSerializerMixin  {
  @override
  final int time;

  @override
  String get type => "testDone";

  // The ID of the test that completed.
  final int testID;

  // The result of the test.
  final String result;

  // Whether the test's result should be hidden.
  final bool hidden;


  factory TestDoneEvent.fromJson(Map<String, dynamic> json) =>
      _$TestDoneEventFromJson(json);

}

error

  LibraryGenerationResultKind.noChange
    The null object does not have a getter 'parameters'.

    NoSuchMethodError: method not found: 'parameters'
    Receiver: null
    Arguments: []
    #0      Object._noSuchMethod (dart:core-patch/object_patch.dart:42)
    #1      Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
    #2      _writeFactory (package:source_gen/generators/json_serializable_generator.dart:104:24)
    #3      JsonSerializableGenerator.generateForAnnotatedElement.<generateForAnnotatedElement_async_body> (package:source_gen/generators/json_serializable_generator.dart:50:20)
    #4      Future.Future.microtask.<anonymous closure> (dart:async/future.dart:144)
    #5      _microtaskLoop (dart:async/schedule_microtask.dart:41)
    #6      _startMicrotaskLoop (dart:async/schedule_microtask.dart:50)
    #7      _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:96)
    #8      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:149)

Copied from original issue: dart-lang/source_gen#79

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.