ig-json-parser icon indicating copy to clipboard operation
ig-json-parser copied to clipboard

Consider support for serialization/deserialization of top level arrays

Open TommyVisic opened this issue 10 years ago • 7 comments

I didn't see a built-in way to handle top-level arrays, e.g.:

[
  {
    "name": "Jorge",
    "faveNumber": 4
  },
  {
    ...
  }
]

Our current solution is to iterate through the array, making calls to the appropriate JsonHelper type for each object. Not a big deal really, but we'd need to duplicate this for each kind of model that's in a top-level array, since I don't see a way to generalize this into a helper method (anyone else?).

List<Video> videos = new LinkedList<Video>();
if (parser.nextToken() == JsonToken.START_ARRAY) {
   while (parser.nextToken() != JsonToken.END_ARRAY) {
      Video video = Video__JsonHelper.parseFromJson(parser);
      videos.add(video);
   }
}

Maybe JsonHelper types could know how to serialize/deserialize arrays of their model types. Something like:

public static final List<MyModel> parseFromJsonArray(JsonParser jp)

TommyVisic avatar Sep 22 '14 22:09 TommyVisic

I stumbled into the same problem. The only way I found to generalize this easily is to use a "closure" although that's not satisfactory. I guess a good way to make it possible would be either to generate a specific method for each Parser or to make them implement a kind of interface with the method parseFromJson().

rtmvc avatar Sep 26 '14 22:09 rtmvc

In case someone needs it, I've created a small gist to help parse a JSON stream knowing its corresponding Java class: https://gist.github.com/ratamovic/c6497504cd8edf87ef38

rtmvc avatar Sep 28 '14 15:09 rtmvc

this is a good start though be aware that this is not proguard safe.

ttung avatar Sep 28 '14 21:09 ttung

Where I can find example how to use ParserHelper class? I found the same problem to serialization/deserialization of top level arrays.

willyantows avatar Jan 09 '15 00:01 willyantows

Thank you for reporting this issue and appreciate your patience. We've notified the core team for an update on this issue. We're looking for a response within the next 30 days or the issue may be closed.

ghost avatar Aug 04 '15 19:08 ghost

Looks like this issue has been abandoned. Any update here? It'd be hugely valuable to have. Can also try to dig in and PR a fix with a little guidance.

asarazan avatar Dec 14 '17 22:12 asarazan

A pretty bad¹ but easy solution to whip up: Parse {"dummy_key": YOUR_JSON_ARRAY}.

A slightly less bad solution, but somewhat more complicated solution: Subclass JsonParser, inject in the tokens to create the same sequence of tokens as above.

The best solution is native support in the library, but I have a different day job now. :/

¹ it's bad because it involves allocating a chunk of memory roughly equal to the length of your string.

ttung avatar Dec 19 '17 15:12 ttung