Skip to content

Commit 829e109

Browse files
Added Typenamehandling to Readme k-paxian#6
1 parent 7bfdafe commit 829e109

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

README.md

+50
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,56 @@ OR use it individually on selected class fields, via `@JsonProperty` annotation
231231
String title;
232232
```
233233

234+
## Typenamehandling
235+
236+
With setting the `includeTypeName` property to `true` _dart-json-mapper_ will dump the object type to the JSON output. This ensures, that _dart-json-mapper_ can reconstruct the object with the right type when deserializing.
237+
238+
``` dart
239+
@jsonSerializable
240+
abstract class Business {
241+
String name;
242+
}
243+
244+
@JsonSerializable(includeTypeName: true)
245+
class Hotel extends Business {
246+
int stars;
247+
248+
Hotel(this.stars);
249+
}
250+
251+
@JsonSerializable(includeTypeName: true)
252+
class Startup extends Business {
253+
int userCount;
254+
255+
Startup(this.userCount);
256+
}
257+
258+
@jsonSerializable
259+
class Stakeholder {
260+
String fullName;
261+
List<Business> businesses;
262+
263+
Stakeholder(this.fullName, this.businesses);
264+
}
265+
266+
final jack = Stakeholder("Jack", [Startup(10), Hotel(4)]);
267+
268+
final iterableBusinessDecorator = (value) => value.cast<Business>();
269+
JsonMapper.registerValueDecorator<List<Business>>(
270+
iterableBusinessDecorator);
271+
final String json = JsonMapper.serialize(jack);
272+
final Stakeholder target = JsonMapper.deserialize(json);
273+
274+
expect(target.businesses[0], TypeMatcher<Startup>());
275+
expect(target.businesses[1], TypeMatcher<Hotel>());
276+
```
277+
278+
With setting `JsonMapper.typeNameProperty` you can specify the name of the json property, who will contain the object type:
279+
280+
``` dart
281+
JsonMapper.typeNameProperty = "objectType";
282+
```
283+
234284
And this is it, you are all set and ready to go. Happy coding!
235285

236286

0 commit comments

Comments
 (0)