Question

I have a JSON with dynamic key value. For example:

"location_id": {
  "0": 0,
  "1": 1,
  "2404": "Section 9 Shah Alam - 3.085376,101.522716",
  "272": "Bukit Jelutong - 3.103953,101.527704",
  "545": "Giant Shah Alam - 3.084166,101.549152",
  ...
}

Usually, what I would do to a fixed key value is to define it in a POJO class, like so:

Json:

"location_id": {
  "id" : "hehe",
  "name": "herpderp",
  "location": "Section 9 Shah Alam - 3.085376,101.522716",
  ...
}

POJO will look like this:

private String id;
private String name;
private String location;
...

And by using GsonRequest, it will parse the JSON to the POJO.

But, how do I deserialize a JSON that has dynamic key value?

Was it helpful?

Solution 2

I got it. Thanks @Mattia for the reply.

I only need to put Map<String, String> to get the whole key-value pairs as String.

OTHER TIPS

You need to parse manually your JSON if you have dynamic key value. For example, do a simple request, then in the response callback parse the data.

JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(final JSONObject response) {
            //get a fake property from response
            String title = response.optString("title");
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(final VolleyError error) {
            //handle errors
        }
    }
    ) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            //get request headers
        }
    };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top