ig-json-parser
ig-json-parser copied to clipboard
Consider support for serialization/deserialization of top level arrays
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)
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().
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
this is a good start though be aware that this is not proguard safe.
Where I can find example how to use ParserHelper class? I found the same problem to serialization/deserialization of top level arrays.
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.
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.
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.