Java-如何获取JSON数组中的对象值? [英] Java - How to get object value in JSON array?

查看:2409
本文介绍了Java-如何获取JSON数组中的对象值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面有一个类似JSON的示例,并且我试图获取一些值,例如of的值.

i have a JSON like example below and i'm trying to get some values, for example value of.

results.shipper.id



{
    "results": [
        {
            "updated": false,
            "notification": false,
            "some_data": {
                "id": 15989,
                "pieces": 0,

            },
            "shipper": {
                "updated": false,
                "notification": false,
                "id": 1587,
                "parent": {
                    "updated": false
                },

我正试图通过这种方式获得价值:

I'm trying to get value by this way:

    String test = shipmentData.getJSONObject("shipper").getString("id");

但是它总是抛出异常.我认为,该异常是由于我无法通过结果"数组访问值而引起的.

But it always throws a exception. I think, that exception is caused because of the i am not accessing to the values via "results" array.

我如何轻松获得所需的价值.

How can i easy access to the value what i need.

我试图找到一些助手(Gson,fast-json等),但是使用起来似乎很复杂(我想使用JSON树直接访问即时"值或访问类似于对象的值,则表示.. Object.InnerObject.value).

I tried find some helpers (Gson, fast-json, etc..) but it seems to be a quite complicated for using (i would like to work with JSON tree for direct access to values "on-the-fly" or access to values like to a object, it means.. Object.InnerObject.value ).

所以问题是我该怎么做?

So question is how can i do it right?

谢谢您的任何建议.

推荐答案

需要遍历JSON才能访问id:

JSON needs to be traversed in order to access id:

JSONArray results = shipmentData.getJSONArray("results");
JSONObject first = results.getJSONObject(0);
JSONObject shipper = first.getJSONObject("shipper");
Integer id = shipper.getInt("id");

将int解析为字符串:

Parse int to string:

String id = String.valueOf(shipper.getInt("id"));

这篇关于Java-如何获取JSON数组中的对象值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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