4

I have json structure like this,how I parse the json with help of Gson.I need to store the key values in json object,I tried many example related to dynamic array but dynamic json array without square brace I cannot parse using Gson.Any Solutions or need to do Manual Json Parse?If any one feel duplicate comment the answer below.

{ "Result":[[
      "Title",
      {
        "0": 1323,
        "1": 3358,
        "2": 2123,
        "3": 8536,
        "4": 1399,
        "5": 9303,
        "7": 9732,
        "8": 3433,
        "9": 1383
      }
    ],[
      "Title",
      {
        "0": 1323,
        "1": 3358,
        "2": 2123,
        "3": 8536,
      }
    ]]}
7
  • In your Json data did Title is required... or any thing like Title:xyz Commented Jan 20, 2016 at 9:45
  • @Don'tBenegative "Title" is a object with no key,not like you mentioned. Commented Jan 20, 2016 at 9:49
  • So is it necessary or not to view in your application Commented Jan 20, 2016 at 9:51
  • @Don'tBenegative I need to store all data in object Commented Jan 20, 2016 at 10:06
  • Please post either the error message you're receiving or describe the incorrect behavior along with the code causing it. Commented Jan 20, 2016 at 12:42

3 Answers 3

3

To start, your JSON causes an exception to be thrown because it is invalid - You have an extra comma at the end of the last value in the second example. "3": 8536, should be "3": 8536.

After fixing that, this should be a simple task provided you define your objects correctly. Here is what I came up with:

public class Results {
    @SerializedName("Result")
    List<Result> results;
}

public class Result {
    String title;
    Map<String, Integer> results;
}

From there, the Result class needs to be deserialized in a special fashion, since the fields in the Result class do not directly map to entries in the JSON. Instead, we need to pull off the first and second elements of the JsonArray that is contained within each Result, and parse it accordingly. That looks like this:

public class ResultDeserializer implements JsonDeserializer<Result> {

    @Override
    public Result deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonArray array = json.getAsJsonArray();

        Result result = new Result();
        result.title = array.get(0).getAsString();

        result.results = new LinkedHashMap<String, Integer>();
        for(Entry<String, JsonElement> entry : array.get(1).getAsJsonObject().entrySet()) {
            result.results.put(entry.getKey(), entry.getValue().getAsInt());
        }

        return result;
    }   
}

Note that my example omits error checking. Finally, register this deserializer, and you should be all set:

Gson gson = new GsonBuilder().registerTypeAdapter(Result.class, new ResultDeserializer()).create();

Results results = gson.fromJson(json, Results.class);

for(Result r : results.results) {
    System.out.println("Title = " + r.title);
    for(Entry<String, Integer> entry : r.results.entrySet()) {
        System.out.println("\t " + entry.getKey() + " -> " + entry.getValue());
    }
}

This prints:

Title = Title
     0 -> 1323
     1 -> 3358
     2 -> 2123
     3 -> 8536
     4 -> 1399
     5 -> 9303
     7 -> 9732
     8 -> 3433
     9 -> 1383
Title = Title
     0 -> 1323
     1 -> 3358
     2 -> 2123
     3 -> 8536

I'll leave it to the OP to implement the reverse, that is a serializer for Result to produce the same results.

Sign up to request clarification or add additional context in comments.

1 Comment

Results results = gson.fromJson(json, Results.class); in this line what is json?
1

Found simple way to parse above json using Nested Map in Gson

Result.java

public class Result {
    @SerializedName("formatted_facet_fields")
    Map<String,Map<String,String>> formatted_facet_fields;
}

in response receiving side

 Gson  gson=new Gson();
 Result result = gson.fromJson(json_response, Result.class);

Comments

0

Yes, You can parse nested json object.

if (!exists) {
        keys = json.keys();
        while (keys.hasNext()) {
            nextKeys = (String) keys.next();
            try {

                if (json.get(nextKeys) instanceof JSONObject) {

                    if (exists == false) {
                        getKey(json.getJSONObject(nextKeys), key);
                    }

                } else if (json.get(nextKeys) instanceof JSONArray) {
                    JSONArray jsonarray = json.getJSONArray(nextKeys);
                    for (int i = 0; i < jsonarray.length(); i++) {
                        String jsonarrayString = jsonarray.get(i).toString();
                        JSONObject innerJSOn = new JSONObject(jsonarrayString);

                        if (exists == false) {
                            getKey(innerJSOn, key);
                        }

                    }

                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        }

For complete understanding checkout below: Code Explanation : https://www.youtube.com/watch?v=ZjZqLUGCWxo

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.