4

By browsing around I did successfully manage to create a class that can "opt in" dat:convert by exposing a Map toJson() method and can be json-ified with JSON.encode(myClass), more or less like the following:

//My dummy class
class MyClass{
  String p1;
  String p2;

  Map toJson{
    return {
      'p1':this.p1,
      'p2':this.p2
    }
  }
}

//so I can do
String jsonString = JSON.encode(myClass)

However I'd like to do this even the other way around, like:

String jsonString = '{"p1":"value","p2":"value"}'
MyClass instance = JSON.decode(jsonString)

But so far I've failed to find a way. I know I can build a constructor for my class that initialises it from a map, something like:

String jsonString = '{"p1":"value","p2":"value"}'
MyClass instance = MyClass.fromMap(JSON.decode(jsonString))

However I was looking for a more "symmetric" way using just JSON.encode() and JSON.decode(), is it somehow doable? Am I missing something?

2
  • What about to just hide JSON.decode in constructor? And looks like (it is just my opinion) it is better to call toJson() explicitly, cause if exception is thrown from it, it does not appear in stacktrace (I don't know why). Commented Sep 29, 2016 at 13:57
  • 1
    hmmm, for sure I could, but my question was more about knowing why I can opt into JSON.encode() by exposing toJson() and not the other way around. Commented Sep 29, 2016 at 14:01

1 Answer 1

1

There is no standard way to encode the class in JSON. {"p1":"value","p2":"value"} doesn't contain any information about what class to instantiate. There is also no standard way to create a new class from as string (what library should be used when several contain a class with the same name, ...

As far as I know a reviver can be used for that purpose

reviver(var key, var value) {
  // decode manually
}
final jsonDecoder = new JsonDecoder(reviver);

but the reviver would need to have some hardcoded logic how to recognize what JSON should result in what Dart class and how it should instantiate it and initialize the properties from the JSON.

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.