使用Gson库动态解析未知数据 [英] Using the Gson library to parse unknown data dynamically

查看:123
本文介绍了使用Gson库动态解析未知数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Gson库解析Android Studio中的JSON数据。但数据是通用的..不知道什么键(对象)来到数据中。


在学校对象下 - 有1103这是对象。

在这个对象下面,我们有shoolname,shortname,学生
再次在学生下 - 有id的像2201,2202 ...
这些对象是动态的,不知道是什么回应。



所以问题是如何在android中使用Gson解析这个json字符串?



或其他任何解决方案都是值得欢迎的



  {
schools:{
home:1103,
statelevel:1348
},
school:{
1103:{
schoolname:Indira School,
nameshort:ind,
学生:{
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:{
分数:94,
lastscore:87
}
}
}
}
}

}

I提及了如何使用GSON解析动态JSON字段? ..但在我的情况下没有工作..我也有内部泛型类。


  1. 我在这里找到了解决方案https://stackoverflow.com/a/23473650/7790252
    实现反序列化器来模拟学校和学生这样的类。


解决方案

使用 java.util.Map 这是一个关联的键/值容器,其中键和值是任意对象,并且可以使用Gson与JSON动态对象保持一致。你只需要定义合适的映射(我将这个域折叠起来以节省一些视觉空间):
$ b

  final class Response {
@SerializedName(schools)final HomeSchool school = null;
@SerializedName(学校)最终地图< Integer,School>学校=空;
}

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);



$ b现在,一旦你有了映射,你可以轻松地反序列化你的JSON:



/ p>

  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英迪拉学校

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)< br>
3203 Ram CR: - (94,87)

类型令牌建议部分正确:它们用于反序列化你不能或不具有具体映射的对象,比如某些东西的列表或者某些字符串的映射。在你的情况下,Gson只需分析字段声明来解析地图类型(键和值)。

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.

解决方案

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).

这篇关于使用Gson库动态解析未知数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆