google / json_serializable.dart Goto Github PK
View Code? Open in Web Editor NEWGenerates utilities to aid in serializing to/from JSON.
Home Page: https://pub.dev/packages/json_serializable
License: BSD 3-Clause "New" or "Revised" License
Generates utilities to aid in serializing to/from JSON.
Home Page: https://pub.dev/packages/json_serializable
License: BSD 3-Clause "New" or "Revised" License
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?
From @kevmoo on June 24, 2015 3:1
Copied from original issue: dart-lang/source_gen#52
From @kevmoo on December 28, 2015 20:44
Like int.
Copied from original issue: dart-lang/source_gen#75
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?
This allows you to not have a public constructor, or have a specialized one just for json serialization.
I get error when used generics.
There is case when enum name in dart and in json does not match, it would be nice to have construction like this:
enum FieldType {
@JsonEnum('Text)
text,
@JsonEnum('Number')
number
}
to solve those issues.
I think I've determined the root cause. The fix is a bit weird...
Basically: flutter requires
Not needed, but in process anyway...
There still might be some lingering conflicts w/ the Flutter SDK. I'll dig in once we get this update.
Hello.
For DateTime helper there's no way to deserialize UTC time. Is there workaround for this?
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)));
Should be a lot more efficient.
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;
}
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
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;
}
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.
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!)
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?
fromJson
case.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.
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.
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.
Shipped in json_serializable-0.5.4
Likely here - #167
See https://github.com/dart-lang/pana/pull/325/files/3d8d74c4636965ae9b0c5b76530e033dda67c4aa#r190491139
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!
I didn't actually verify but with the move to mono_repo I am pretty sure this is just bailing early since its not running from the root of the git repo.
I'd prefer to just import the generated file instead of using the part/part of syntax. Is there any reason why the part/part of syntax is required? If it's not, could an option be added to prevent generating it?
From @kevmoo on July 18, 2017 23:24
Copied from original issue: dart-lang/source_gen#217
This error appeared for me when running flutter packages pub run build_runner build
.
This was with my pubspec.yaml set to
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^0.8.0
json_serializable: ^0.5.2
According to dart-lang/build#1463, pinning build_runner to 0.8.8 is the fix.
So use
flutter_test:
sdk: flutter
build_runner: ^0.8.8
json_serializable: ^0.5.2
because dson
exists already.
#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"
From @kevmoo on October 28, 2016 21:29
Copied from original issue: dart-lang/source_gen#96
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
Should explain how this relates to build.yaml and pkg/build, etc
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;
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
I can't do this:
@jsonkey(name: "text", alternate = {"full_text"})
String text;
in gson I can do something like:
@SerializedName(value = "text", alternate = {"full_text"})
public final String text;
From @kevmoo on September 17, 2015 17:25
Copied from original issue: dart-lang/source_gen#62
Even if it's available in the constructor...
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
Instead of hard-wiring to/from Json into each class
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.
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.
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
From @kevmoo on December 10, 2015 1:22
Copied from original issue: dart-lang/source_gen#72
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;
}
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.