2013-06-28 41 views
0

我得到这个JSON字符串:解析到时的JSONObject没有被正确创建(可以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语法IM(在iOS应用正常工作),但是JSONObject它捕获错误。 Java:

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中某处出现错误吗?

回答

4

[表示JSON数组节点

{表示JSON对象节点

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

您也可以有一个try块而不是许多。

+0

感谢JSONArray!这里最好的解释,谢谢!我会接受它,当它允许:) –

+0

@JoshBoothe欢迎您。你也可以有一个try块,并且有很多基于异常层次的catch块 – Raghunandan

+0

@Raghunandan好解释 – Blackbelt

0

这是一个数组,因此您需要执行“new JSONArray()”而不是“new JSONObject()”。

0

当一个JSON字符串[开始,将被视为您需要做的new JSONArray()

相关问题