解析java

时间:2016-06-02 15:58:42

标签: java json jsonobject

我做了一个http客户端,我收到了回复。我使用JSONObject来解析数据,当我执行下面的代码时,它打印出所有的JSON就好了

HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if(entity!=null){
            try(InputStream instream = entity.getContent()) {
                String responseString = readInputStream(instream);
                JSONObject job = new JSONObject(responseString);
                statusLabel.setText("Command Result: " + job.toString());

这是readInputSream函数:

static private String readInputStream(InputStream inputStream) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            inputStream, "UTF-8"));
    String tmp;
    StringBuilder sb = new StringBuilder();
    while ((tmp = reader.readLine()) != null) {
        sb.append(tmp).append("\n");
    }
    if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\n') {
        sb.setLength(sb.length() - 1);
    }
    reader.close();
    return sb.toString();
}

如果我将它从job.toString()更改为:

statusLabel.setText("Command Result: " + job.get("result"));

它打印1是正确的,它一直工作到my_list。我不确定如何解析列表。我在下面放了一个响应片段。我试过“my_list”,“my_list []”,my_list [0]“没有用过。我得到JSONObject”空白“未找到

{"result":1,  "ver":1,"total":2,"catch":true,"my_list":[{"id":3,"mid":0,"format":3,"user":4,"property":1,"type":0,"title":"hello","start":146,"end":1464,"hid":3,"bid":1,"reason":1,"time":0,"creator":"1","hello":0,"my":0,"year":"0","ggg":614,"name":"","ch":"0","attr":0,"type":1,"vtype":1,"tm_log": {"fr":4,"action":0,"vr":"82","started":1,"av_ended":2,"tr":1}}

2 个答案:

答案 0 :(得分:2)

您尝试检索的元素被解析为JSONArray,而不是JSONObject。尝试:

JSONArray my_list = job.getJSONArray("my_list");

答案 1 :(得分:1)

假设您正在使用json解析器项目JSON-java来解析您的JSON,您需要检索JSONArray实例 - 这就是在JSONObject中存储数组的方式。所以执行以下操作:JSONArray my_list = job.getJSONArray("my_list");然后使用JSONArray类的方法来访问您的数组。可以在此处找到Javadoc到JSON-java包:http://stleary.github.io/JSON-java/index.html。另请注意,JSON-java是非常简单易用的JSON解析器项目,但对于任何严肃的项目来说都不是很有效。商业用途的常见建议是Jackson JSON处理器,它是速度最快且功能最强大的JSON解析器之一。以下是一些可供阅读的链接:https://github.com/FasterXML/jacksonhttp://wiki.fasterxml.com/JacksonHome