在不使用Java中的POJO类的情况下解析不同的JSON响应 [英] Parse different JSON responses without using POJO classes in Java

查看:154
本文介绍了在不使用Java中的POJO类的情况下解析不同的JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中解析来自REST API的JSON响应,但我不想为每个响应创建一个Java类(POJO)(响应具有不同的数据结构和字段)。 Java中是否有一个更通用的JSON解析器,类似于JavaScript的直接语法?

I am parsing JSON responses from REST API in Java, but I don't want to create a Java class (POJO) for each response (responses have different data structures and fields). Is there a more generic JSON parser in Java that is similar to the straightforward syntax of JavaScript?

下面的JSON是众多REST端点中的一个的结果

The JSON below is the result of just one of the many REST endpoints

{
    "f1" : "volume",
    "f2" : "gender",
    "f3" : "days",
    "f4" : [{
            "id" : "F",
            "name" : "female",
            "values" : [{
                    "name" : "September",
                    "value" : 12
                }
            ]
        }, {
            "id" : "M",
            "name" : "male",
            "values" : [{
                    "name" : "September",
                    "value" : 11
                }
            ]
        }
    ]
}

在JavaScript中,要访问女性的值:

In JavaScript, to access the value for female:

jsonRoot.f4[0].values[0].value

这比创建大量Java类更整洁。你可以建议类似的东西或避免创建许多POJO的方法吗?

which is neater than to have to create numerous Java classes. Can you suggest something similar or a way to avoid creating many POJOs?

推荐答案

如果您导入了 com的jar。 google.gson 。你可以得到这样的值:

If you imported the jar of com.google.gson.You can get the value like this:

     String str="{" +
            "    \"f1\" : \"volume\"," +
            "    \"f2\" : \"gender\"," +
            "    \"f3\" : \"days\"," +
            "    \"f4\" : [{" +
            "            \"id\" : \"F\"," +
            "            \"name\" : \"female\"," +
            "            \"values\" : [{" +
            "                    \"name\" : \"September\"," +
            "                    \"value\" : 12" +
            "                }" +
            "            ]" +
            "        }, {" +
            "            \"id\" : \"M\"," +
            "            \"name\" : \"male\"," +
            "            \"values\" : [{" +
            "                    \"name\" : \"September\"," +
            "                    \"value\" : 11" +
            "                }" +
            "            ]" +
            "        }" +
            "    ]" +
            "}";
    JsonParser parser=new JsonParser();
    JsonObject object=(JsonObject)parser.parse(str);
    String value=object.get("f4").getAsJsonArray().get(0).getAsJsonObject()
            .get("values").getAsJsonArray().get(0).getAsJsonObject()
            .get("value").getAsString();

这篇关于在不使用Java中的POJO类的情况下解析不同的JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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