Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON parsing dynamic JSON field

Tags:

java

gson

I can't seem to figure this out. I've looked at a couple SO posts (here, and here), and my situation is just a little different.

I'm not sure if I have to register a new TypeToken or what. But my JSON object looks like this:

{
    "id": 6,
    "error": "0",
    "dates": {
        34234 : "2011-01-01" // I want to parse the date into a string.
        87474 : "2011-08-09" // The first values are all unique.
        .                    //this can be any number of entries.
        .
        .
        74857 : "2011-09-22"
    }
}

I've created both of my objects like this:

public class Response {

    public Integer id;
    public String error;
    public DateList dates;
}

Separate file:

public class DateList {

    public List<Map<Integer, String>> dateString;
}

I'm not sure how to tweek it to get it right. Documentation doesn't seem to help... And the other examples I've seen are parsing a custom object, not a string type.

Thanks!

like image 406
Matt W. Avatar asked Oct 04 '11 17:10

Matt W.


People also ask

What is dynamic JSON?

A dynamic JSON file will be created to store the array of JSON objects. Consider, we have a database named gfg, a table named userdata. Now, here is the PHP code to fetch data from database and store them into JSON file named gfgfuserdetails. json by converting them into an array of JSON objects.

Does JSON parse automatically?

The JSON file will be parsed for you automatically and you can start using it in your project: const jokes = require('./jokes. json'); console.

How do I deserialize JSON with GSON?

Deserialization in the context of Gson means converting a JSON string to an equivalent Java object. In order to do the deserialization, we need a Gson object and call the function fromJson() and pass two parameters i.e. JSON string and expected java type after parsing is finished. Program output.


1 Answers

I tried it in this form:

The Json

{
    "id": 6,
    "error": "0",
    "dates": {
        "34234" : "2011-01-01"
        "87474" : "2011-08-09"
        "74857" : "2011-09-22"
    }
}

And the Response.java

public class Response {
    public Integer id;
    public String error;
    public Map<Integer, String> dates;
}

At least that seemed to work out of the box.

like image 158
M.L. Avatar answered Sep 30 '22 17:09

M.L.