如何解码JSONObject [英] How to decode JSONObject

查看:115
本文介绍了如何解码JSONObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与我以前的有关问题

我可以从URL到spring控制器成功获取json格式的字符串

I can successfully get the String in json format from the URL to my spring controller

现在我必须对其进行解码

Now I have to decode it

所以我确实喜欢以下内容

so I did like the following

@RequestMapping("/saveName")
@ResponseBody
public String saveName(String acc)
{jsonObject = new JSONObject();
    try
    {
   System.out.println(acc);
    org.json.JSONObject convertJSON=new org.json.JSONObject(acc);

    org.json.JSONObject  newJSON = convertJSON.getJSONObject("nameservice");
    System.out.println(newJSON.toString());
    convertJSON = new org.json.JSONObject(newJSON.toString());
    System.out.println(jsonObject.getString("id"));

    }
    catch(Exception e)
    {
        e.printStackTrace();jsonObject.accumulate("result", "Error Occured ");
    }
    return jsonObject.toString();
}

这是JSON字符串{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }

运行代码时出现错误

org.json.JSONException: JSONObject["nameservice"] is not a JSONObject.

我在做什么错?

推荐答案

不是JSONObject,而是JSONArray

根据您的问题:

{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }

nameservice关键字后的[告诉您这是一个数组.它必须是{来表示一个对象,但不是

The [ after the nameservice key tells you it's an array. It'd need to be a { to indicate an object, but it isn't

因此,更改您的代码以将其用作JSONArray,然后遍历其内容以在其中获取JSONObjects,例如

So, change your code to use it as a JSONArray, then iterate over the contents of that to get the JSONObjects inside it, eg

JSONArray nameservice = convertJSON.getJSONArray("nameservice");
for (int i=0; i<nameservice.length(); i++) {
   JSONObject details = nameservice.getJSONObject(i);
   // process the object here, eg
   System.out.println("ID is " + details.get("id"));
   System.out.println("Name is " + details.get("name"));
}

有关更多详细信息,请参见 JSONArray javadocs

See the JSONArray javadocs for more details

这篇关于如何解码JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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