繁体   English   中英

从Java中的JSON对象中的数组获取价值?

[英]Getting value from an array in a JSON Object in Java?

我对Java中的REST API调用是相当陌生的,并且目前在尝试从JSON对象(如下)获取“ item”部分时遇到问题。 我猜这也使我感到困惑,“响应”也是数组中的一个对象?/

JSON文件如下:

{
"version": "1.0",
"code": 200,
"request":{"text":["seafood" ], "lang": "en", "type": "stimulus"},
"response":[{
    "text": "seafood",
    "items":[
         {"item": "Shrimp", "weight": 100, "pos": "noun" }, 
         {"item": "Lobster",…
     ]
}]
}

我目前设法使用以下方法获取对象的“响应”部分:

BufferedReader in = new BufferedReader( 
    new InputStreamReader(conection.getInputStream()));
StringBuffer json = new StringBuffer();
while ((readLine = in.readLine()) != null) {
    json.append(readLine);
} 
in.close();
JSONParser parser = new JSONParser();
try{
    JSONObject object= (JSONObject) parser.parse(json.toString());
    Object response = json.get("response");
...

到目前为止,我陷入困境。 我不知道该如何处理“响应”以获取“项目”,如果我尝试将“响应”转换为JSONObject,它将返回为null?

我想尝试做的是将“项目”部分中的每个“项目”都放入列表中。

帮助将不胜感激!

我认为应该可以:

JSONParser parser = new JSONParser();
try{
    JSONObject object= (JSONObject) parser.parse(json.toString());
    JSONArray response = object.getJSONArray("response");
    JSONObject responseObject = response.getJSONObject(0);
    JSONArray expectedArray = responseObject.getJSONArray("items");
    for (int i = 0; i < expectedArray.length(); i++) {
        String item = expectedArray.getJSONObject(i).getString("item");
        String weight = expectedArray.getJSONObject(i).getInt("weight");
        ......
        //Here you can create your custom object and add to your array. For example
        list.add(new MyOwnObject(item, weight));
    }
....

因为响应是数组,而不是对象

您应该检查JSONObject的文档 它描述了所有可用的方法。 请注意,没有名为get()方法。 相反,您可能想使用getJSONArray()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM