json - 使用Gson库动态解析未知数据

标签 json generics gson

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

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
                }
            }
        }
    }
}

}

我引用了How to parse dynamic JSON fields with GSON? ..但在我的情况下不起作用..我也有内部通用类。
  • 我在这里找到了解决方案 https://stackoverflow.com/a/23473650/7790252 .
    实现反序列化器来模拟学校和学生等类。
  • 最佳答案

    您可以简单地使用 java.util.Map这是一个关联的键/值容器,其中键和值是任意对象,并且可以使用 Gson 非常直接地与 JSON 动态对象对齐。您只需要定义适当的映射(我将字段折叠起来以节省一些视觉空间):

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

    现在,一旦你有了映射,你就可以轻松地反序列化你的 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)



    类型标记建议部分正确:它们用于反序列化您不能或没有具体映射的对象,例如某物的列表或字符串到某物的映射。在您的情况下,Gson 仅分析字段声明以解析映射类型(键和值)。

    关于json - 使用Gson库动态解析未知数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43111401/

    相关文章:

    android - 错误 : incompatible types: GsonConverterFactory cannot be converted to Factory

    php - json_encode 在 array_filter 之后有不同的结果

    json - 为什么根据其他工具,来自aws rds的JSON在Docker "malformed"中运行?

    python - Django - 异常处理最佳实践和发送自定义错误消息

    c# - 泛型方法类型参数的类型推断

    c# - 如何使用 GSON 将 JSON 值映射到不同的类

    javascript - 如何在 javaScript 中使用特定键对对象进行分组

    java - GenericDao<Order,capture#2-of ?> 类型中的方法 read(capture#2-of ?) 不适用于参数 (Long)

    java - 使用泛型类型的嵌入式泛型

    java - 在 Android 上使用 GSON 将 JSON 日期格式解析为字符串