0

Flutter App, API backend exchanging array of nested objects in JSON format.
Setting up JSON serialization / deserialization with the following articles, using json_serializable:
https://docs.flutter.dev/data-and-backend/serialization/json

https://docs.flutter.dev/cookbook/networking/background-parsing

Created nested classes, with the proper annotation (@JsonSerializable(explicitToJson: true) and successfully created .g.dart files. Deserialization works perfectly with the following code:

List<MyModel> myNestedObjVar = deserialize(String apiResponse);

List<MyModel> deserialize(String data) {
    final parsed = (jsonDecode(data) as List).cast<Map<String, dynamic>>();
    return parsed
    .map<MyModel>((json) => MyModel.fromJson(json))
    .toList();
}

What I am looking for is how to get the JSON string back, something like:

String myStrVar = serialize(myNestedObjVar);

String serialize(List<MyModel> data) {
    ???
}

There are lot of questions / websites who explain in details deserialization of nested objects, but none who explain the inverse process of serialization. Obvious, it is the inverse of the above deserialize function (here the code is compacted) but I cannot understand each inner step and then how to reverse it.
Any help is apreciated.
Thanks.

1 Answer 1

0

just use the jsonEncode and toJson functions like you did with jsonDecode and fromJson


String serialize(List<MyModel> data) {
     final list = data.map((map) => map.toJson()).toList();
     return jsonEncode(list);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.