解析嵌套的JSON数据时出错

时间:2013-06-18 17:43:40

标签: java android json parsing

我在解析我的JSON文件时面临“解析数据时出错”错误

解析以下文本时,解析器似乎适用于这些:

{"vid":"2",
"uid":"1",
"title":"BangsarSouth",
"log":"",
"status":"1",
"comment":"1",
"promote":"0",
"sticky":"0",
"nid":"2",
"type":"property",
"language":"und",
"created":"1369825923",
"changed":"1370534102",
"tnid":"0"

但是一旦它到达文件的这一部分,它就会崩溃并给我一个解析错误

"body":{"und":[{"value":"Some description for Bangsar South.\r\nLorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.","summary":"","format":"filtered_html","safe_value":"<p>Some description for Bangsar South.<br />\nLorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam等......

我怀疑错误是由嵌套元素引起的。有人可以为我的问题提出解决方案吗?

下面是我的javacode

try {

        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://xxxxxx.com/rest/node/2.json");

        HttpResponse response = httpClient.execute(httpGet);
         HttpEntity entity = response.getEntity();
         is = entity.getContent();


    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection "+e.toString());
    }

    try {           
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
        }
        is.close();

        result=sb.toString();
        Log.e("faridi",result);


    } catch (Exception e) {
        Log.e("log_tag", "Error converting result "+e.toString());
    }


    //parse json data
    try{
            jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){

                    JSONObject json_data = jArray.getJSONObject(i);

                }
    }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }

1 个答案:

答案 0 :(得分:0)

杰克逊和春天将成为你的朋友。

你可以使用Spring的RestTemplate库,它使用jackson来完成所有繁重的JSON工作。

为了理智,我们可以说这是回复的JSON响应。

{
    "message" : "Hello World",
    "answer" : "42"
}

现在你做的第一件事就是“反序列化”成Pojo。做一些谷歌杰克逊反序列化的谷歌搜索,你应该好好去。

如果你曾经使用过JAXB解组xml,那么你就会在家里。它非常简单,只需制作一个Json响应的Pojo容器。

@JsonSerialize
public class JsonResponse {
    private String message;
    private int answer;
    // Getters and seters below.
}

然后你需要RestTemplate进行Json Rest调用并为你创建JsonResponse对象。

因为,你只是在做一个HTTP GET方法,这是最简单的方法。

RestTemplate restTempalte = new RestTemplate();
JsonResponse jsonResponse = restTemplate.getForObject("url", JsonResponse.class);

除了简单的单行内容之外,还可以轻松模拟单元测试的REST响应。

如果您需要有关传输的任何数据,请使用getForEntity()。