Flutter, Dart: How to serialize Json to Class with nested Classes

So, this example from flutter docs

import 'package:json_annotation/json_annotation.dart';
part 'address.g.dart';
@JsonSerializable()
class Address {
String street;
String city;
Address(this.street, this.city);

factory Address.fromJson(Map<String, dynamic> json) =>_$AddressFromJson(json);Map<String, dynamic> toJson() => _$AddressToJson(this);
}

Then it becomes nested class in class User.


import 'package:json_annotation/json_annotation.dart';

import 'address.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
User(this.name, this.address);

String name;
Address address;

factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}

So, ok, it works with JSON {name: John, address: {street: My st., city: New York}}. My question is how to make it work with JSON like this {name: John, street: My st., city: New York}

I've been trying to find anything in the documentation of json_serializable package, but I didn't find anything that helped me.

Yes we can do DTO class to this JSON, and then make another classes as we want.But maybe there is another way?

Upvotes: 0

Views: 254

Answers (0)

Related Questions