dplesa
dplesa

Reputation: 1415

Parse Json with Gson and problems with list

I used a Gson to parse JSON String returned from external API to representing Java class. Everything works fine but I have one problem which I'm unable to solve.

The problem is that external API sometimes returns a JSON like this:

{ Token: { TokenId : '123' } }

and sometimes JSON like this:

{ Token: [{ TokenId : '123' }, { TokenId : '124' }] }

If my class is set to contain a list of Tokens then Gson will not be able to parse the JSON from first example. How can I manage to parse JSON in both cases?

Upvotes: 1

Views: 457

Answers (2)

Ramachandran.A.G
Ramachandran.A.G

Reputation: 4948

A quick way of doing it is as follows

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

public class Clazz {
    public static void main(String[] args) throws Exception {

    String singularJson = "{ Token: { TokenId : '123' } }";
    String multipleJson = "{ Token: [{ TokenId : '123' }, { TokenId : '124' }] }";

    JsonElement jsonElementToken = new JsonParser().parse(multipleJson);
    JsonElement jsonCollectionOrSingular = jsonElementToken.getAsJsonObject().get("Token");
    if (jsonCollectionOrSingular.isJsonArray()) {
        System.out.println("It is an collection and not a object");
        JsonArray jsonArray = jsonCollectionOrSingular.getAsJsonArray();
        System.out.println(jsonArray.get(0).getAsJsonObject().get("TokenId"));

    } else {
        System.out.println("It is an object and not a collection");
        JsonObject jsonObject = jsonCollectionOrSingular.getAsJsonObject();
        System.out.println(jsonObject.get("TokenId"));

    }

}

Upvotes: 1

Mohamed Anees A
Mohamed Anees A

Reputation: 4591

Convert all the response to look something like the second example before converting to class.

Below would serve as the hint

jsonString=jsonString.replace("{ Token: {","{ Token: [{");
jsonString=jsonString.replace("} }","}] }");

Upvotes: 0

Related Questions