4

I want to parse following JSON data in Android Studio using Gson library. But the data is generic..dont know what keys(objects) are come in data..

under school object - there is number 1103 which is object.

and under that object we have shoolname, shortname, students again under students - there are id's like 2201, 2202... these objects are dynamic dont know what comes in response..

so question is how to parse this json string in android using Gson?

or any other solution for that is welcome

{
"schools": {
    "home": "1103",
    "statelevel": "1348"
},
"school": {
    "1103": {
        "schoolname": "Indira School",
        "nameshort": "ind",
        "students": {
            "2201": {
                "name": "Ritesh",
                "isCR": true,
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "2202": {
                "name": "Sanket",
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "2203": {
                "name": "Ajit",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    },
    "1348": {
        "schoolname": "Patil School",
        "nameshort": "pat",
        "students": {
            "3201": {
                "name": "Ravi",
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "3202": {
                "name": "Raj",
                "isCR": true,
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "3203": {
                "name": "Ram",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    }
}

}

I have refered the How to parse dynamic JSON fields with GSON?.. but not worked in my case..i have inner generic classes too.

  1. I have found the solution here https://stackoverflow.com/a/23473650/7790252. implements deserializer to model classes like school and students.
Community
  • 1
  • 1
Ritesh Bhavsar
  • 1,343
  • 1
  • 9
  • 19
  • 1
    Possible duplicate of [How to parse dynamic JSON fields with GSON?](http://stackoverflow.com/questions/5796948/how-to-parse-dynamic-json-fields-with-gson) – Oğuzhan Döngül Mar 30 '17 at 07:45
  • @oguzhand : partially duplicate..in my case i have to parse whole json into my pojo class..Duplicate in case if i have json after "school:"->{1103...}..then it worked..but for inner json again has students..it didnt worked. – Ritesh Bhavsar Mar 30 '17 at 10:28

3 Answers3

3

You can simply use java.util.Map that is an associative key/value container where keys and values are arbitrary objects, and can align with JSON dynamic objects using Gson really straight-forward. You just have to define appropriate mappings (I made the field collapsed to save some visual space):

final class Response {
    @SerializedName("schools") final HomeSchool school = null;
    @SerializedName("school") final Map<Integer, School> schools = null;
}

final class HomeSchool {
    @SerializedName("home") final int home = Integer.valueOf(0);
    @SerializedName("statelevel") final int stateLevel = Integer.valueOf(0);
}

final class School {
    @SerializedName("schoolname") final String name = null;
    @SerializedName("nameshort") final String shortName = null;
    @SerializedName("students") final Map<Integer, Student> students = null;
}

final class Student {
    @SerializedName("name") final String name = null;
    @SerializedName("isCR") final boolean isCr = Boolean.valueOf(false);
    @SerializedName("maths") final Maths maths = null;
}

final class Maths {
    @SerializedName("score") final int score = Integer.valueOf(0);
    @SerializedName("lastscore") final int lastScore = Integer.valueOf(0);
}

Now, once you have the mappings, you can easily deserialize your JSON:

private static final Gson gson = new Gson();

public static void main(final String... args) {
    final Response response = gson.fromJson(JSON, Response.class);
    for ( final Entry<Integer, School> schoolEntry : response.schools.entrySet() ) {
        final School school = schoolEntry.getValue();
        System.out.println(schoolEntry.getKey() + " " + school.name);
        for ( final Entry<Integer, Student> studentEntry : school.students.entrySet() ) {
            final Student student = studentEntry.getValue();
            System.out.println("\t" + studentEntry.getKey()
                    + " " + student.name
                    + " CR:" + (student.isCr ? "+" : "-")
                    + " (" + student.maths.score + ", " + student.maths.lastScore + ")"
            );
        }
    }
}

1103 Indira School
2201 Ritesh CR:+ (95, 86)
2202 Sanket CR:- (98, 90)
2203 Ajit CR:- (94, 87)
1348 Patil School
3201 Ravi CR:- (95, 86)
3202 Raj CR:+ (98, 90)
3203 Ram CR:- (94, 87)

The type token suggestions are partially correct: they are used to deserialize the objects you cannot or don't have concrete mappings for, like lists of something, or maps of strings to something. In your case Gson simply analyzes the field declarations to resolve the map types (both keys and values).

Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105
0

From Gson Documentation

 Type mapType = new TypeToken<Map<Integer, Result> >() {}.getType(); // define generic type
Map<Integer, Result> result= gson.fromJson(new InputStreamReader(source), mapType);
Mich
  • 71
  • 13
0

Create model object which implements JsonDeserializer

then you have this method to override:

@Override
public ActivityEvents deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    JsonObject jObject = jsonElement.getAsJsonObject();
    for (Map.Entry<String, JsonElement> entry : jObject.entrySet()) {
    entry.getKey(); //here you can get your key 
    gson.fromJson(entry.getValue(), StudebtInfo.class);; //here you can get value for key
    }
}
Lalit Jadav
  • 1,409
  • 1
  • 15
  • 38
  • What problem you are facing? – Lalit Jadav Mar 30 '17 at 10:06
  • i have created classes for School,ResultSchool(generic i.e for 1103, 1348), Students, Resultstudents(generic for 2201...)..in resultschool i have implemented deserializer..in deserialize()..what should i write i dint get..I have refered link ..** return new Resultschool(json.getAsJsonPrimitive().getAsString()) ** but not worked – – Ritesh Bhavsar Mar 30 '17 at 10:30