Skip to content
Advertisement

How can I dynamically find the end of an object array inside of a JSON response using GSON?

I am working with a given JSON response. The API I’m using provides responses like such:

 {
 "data":[
  { 
    "sample-value": "sample"
  }
  {
    "sample-value": "sample"
  }
  { 
    "sample-value": "sample"
  }
  {
    "sample-value": "sample"
  }
 ],
    "meta": {
        "current-page": 1,
        "next-page": 2,
        "prev-page": null,
        "total-pages": 5,
        "total-count": 4338,
        "filters": {}
    },
"links": {



        "self": "linktothisquery",
        "next": "linktonextquery",
        "last": "linktolastpagequery"
    }
}

As you can see, the response provided contains what I interpret to be 1 object array (size changes depending on what is being queried) and 2 objects. (data is the array, meta and links are the objects) I have ran into a situation where I need to run multiple requests in order to get the full amount of data required for my project. I’m attempting to get around this by iterating through requests, but due to the variance in response length per-request I cannot use the same logic to locate only the array in the response and thus end up with unexpected characters making GSON unable to parse. I’m currently doing this by using String.substring() and manually inputting the location inside of the response that I want GSON to parse. Basically, I want GSON to ONLY see the “data” array and ignore everything else. I have model classes in my project to serialize the data, but they are built around the objects inside of the afforementioned array and not the array itself.

Advertisement

Answer

Your posted JSON is invalid .In data array comma is missing in between two objects. It should be

{ 
    "sample-value": "sample"
},
{
    "sample-value": "sample"
}

Now if you just want the data array part you can manually parse it using JsonParser. It will be the easiest way to do it.

String json = "{"data":[{"sample-value":"sample"},{"sample-value":"sample"},{"sample-value":"sample"},{"sample-value":"sample"}],"meta":{"current-page":1,"next-page":2,"prev-page":null,"total-pages":5,"total-count":4338,"filters":{}},"links":{"self":"linktothisquery","next":"linktonextquery","last":"linktolastpagequery"}}";

JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();       
JsonArray jsonArray =  jsonObject.get("data").getAsJsonArray();

jsonArray.forEach(System.out::println);

Output:

{"sample-value":"sample"}
{"sample-value":"sample"}
{"sample-value":"sample"}
{"sample-value":"sample"}
Advertisement