【问题标题】:JSONObject not being correctly created (possible JSON formatting error?)JSONObject 未正确创建(可能的 JSON 格式错误?)
【发布时间】:2013-06-28 14:00:37
【问题描述】:

我得到这个 JSON 字符串:

[
{
    "id": 135,
    "date": "2013-08-30 19:00:29",
    "timestamp": "2013-08-30 19:00:29",
    "lat": "54.328274",
    "long": "-2.747215",
    "strap": "annual International Festival of Street Arts",
    "link": "http://dev.website.co.uk//?p=135",
    "title": "Title"
}
]

我确定哪种 JSON 语法是正确的(在 iOS 应用程序中可以正常工作),但是在解析为 JSONObject 时会发现错误。爪哇:

public static JSONObject getJSONfromURL(String url){

    //initialize
    InputStream is = null;   
    String result = "";   
    JSONObject jArray = null;

    //http post
    try {

        HttpClient httpclient = new DefaultHttpClient();   
        HttpPost httppost = new HttpPost(url);    
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

        is = entity.getContent();    

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection "+e.toString());   
    }
    //convert response to string

    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();

    } catch (Exception e) {    
        Log.e("log_tag", "Error converting result "+e.toString());
    }
    //try parse the string to a JSON object

    try {
        Log.d("log_tag", "jresult: " + result + "finish");
        jArray = new JSONObject(result);

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

JSON 中是否有错误?

【问题讨论】:

    标签: java android json


    【解决方案1】:

    [代表一个json数组节点

    {代表一个json对象节点

        JSONArray jArray  = new JSONArray(result);
        return jArray;  
    

    您也可以使用一个 try 块而不是多个。

    【讨论】:

    • 谢谢!最好的解释在这里,所以谢谢!我会在允许的时候接受它:)
    • @JoshBoothe 不客气。你也可以有一个 try 块并有许多基于异常层次结构的 catch 块
    【解决方案2】:

    这是一个数组,所以你需要做“new JSONArray()”而不是“new JSONObject()”。

    【讨论】:

      【解决方案3】:

      当 json 字符串以 [ 开头时,它将被视为 JSONArray 您需要执行 new JSONArray()

      【讨论】:

        猜你喜欢
        • 2016-01-14
        • 2017-01-19
        • 2016-11-18
        • 2018-02-28
        • 2011-04-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多