簡體   English   中英

解析嵌套的JSON數據時出錯

[英]Error when Parsing Nested JSON Data

解析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());
    }

傑克遜和斯普林將是你的朋友。

您可以使用Spring的RestTemplate庫,該庫將jackson用於所有繁重的JSON工作。

為了理智,可以說這是返回的JSON響應。

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

現在,您要做的第一件事就是“反序列化”為Pojo。 對Java Jackson反序列化進行一些谷歌搜索,您應該很好。

如果您以前使用過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()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM