我如何从Json对象和数组中获取数据

时间:2019-05-07 22:57:29

标签: java json

我收到请求,但无法从json对象获取jsonarray。

JSONObject ob = JSONObject.fromObject(response.toString());

JSONArray arr = ob.getJSONArray("results");

for (int i = 0; i < arr.size(); i++) {
    JSONObject jsonAuth = arr.getJSONObject(i);
    String PREFIX = jsonAuth.get("PREFIX").toString();
}

我的json:

{
    "d": {
        "results": [{
            "__metadata": {
                "type": "ceodo.cco.loc_do.OdataV2.SecuenciasType",
                "uri": "com:443/ceodo/cco/loc_do/OdataV2.xsodata/Secuencias('d76fffbe-8c3b-4c66-bd7f-16c9d099d143')"
            },
            "SEC_ID": "d76fffbe-8c3b-4c66-bd7f-16c9d099d143",
            "PREFIX": "B",
            "TIPO_NCF": "01",
            "NUM_FROM": 50,
            "NUM_TO": 100,
            "NUM_CURRENT": 25,
            "VALID_UNTIL": "\/Date(1556582400000)\/",
            "CAJA": "b1c913fc-e319-476f-8295-64782b77de52"
        }, {
            "__metadata": {
                "type": "ceodo.cco.loc_do.OdataV2.SecuenciasType",
                "uri": "com:443/ceodo/cco/loc_do/OdataV2.xsodata/Secuencias('f3323600-6bf2-4e90-8856-56390595d748')"
            },
            "SEC_ID": "f3323600-6bf2-4e90-8856-56390595d748",
            "PREFIX": "B",
            "TIPO_NCF": "02",
            "NUM_FROM": 1,
            "NUM_TO": 100,
            "NUM_CURRENT": 35,
            "VALID_UNTIL": "\/Date(1554249600000)\/",
            "CAJA": "c90030fb-030b-4a99-929a-adc72eaf082f"
        }]
    }
}

1 个答案:

答案 0 :(得分:0)

好吧,您可以先调用'd'对象。

您的json文件的顺序应该从d(JSONObject)标记到results(JSONArray)标记。

这里是使用另一个json library

的代码
import org.json.JSONArray;
import org.json.JSONObject;

... skip ...

//JSONObject ob = JSONObject.fromObject(resBuf.toString());
JSONObject ob = new JSONObject(resBuf.toString());
if(ob.has("d"))
{
    JSONObject dobj = ob.getJSONObject("d");

    if(dobj.has("results"))
    {
        JSONArray arr = dobj.getJSONArray("results");

        System.out.println(arr.length());

        for (int i = 0; i < arr.length(); i++) {
            JSONObject jsonAuth = arr.getJSONObject(i);
            String PREFIX = jsonAuth.get("PREFIX").toString();
            System.out.println(PREFIX);
        }
    }

}