2012-05-23 16 views
2

我想下面的JSON转换成一个Android应用程序时:org.json.JSON.typeMismatch将字符串转换成

[ 
    { 
     "patient_id": "16", 
     "patient_firstname": "Ion", 
     "patient_name": "Vasilescu", 
     "location": "Cardiologie, Salon 4, Pat 2" 
    }, 
    { 
     "patient_id": "22", 
     "patient_firstname": "Claudiu", 
     "patient_name": "Popovici", 
     "location": "Pneumologie, Salon 5, Pat 5" 
    }, 
    { 
     "patient_id": "15", 
     "patient_firstname": "Monica", 
     "patient_name": "Suciu", 
     "location": "Cardiologie, Salon 4, Pat 2" 
    } 
] 

我已经通过呈三角问题和答案,但在我的情况我不读看不到任何语法问题。我用JSONLint检查了JSON并验证成功。

我的Java代码如下:

public JSONObject toJson(String jString){ 
    System.out.println("I've got"+jString+"*"); 

    try { 
     return new JSONObject(jString); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     System.out.println("Error while converting to JSONObject"); 
    } 

    return null; 
} 

有谁知道如何摆脱我的错误的建议吗?或者如何实施更好的解决方案?谢谢。

+0

很好的解释教程:http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ –

+0

什么是你得到的错误?请发布完整的堆栈跟踪。 – Perception

回答

4

将JSONObject替换为JSONArray,因为它的数组是!

3

你得到的结果作为一个JSON数组不是JSON字符串,尝试改变slass

您的代码:

public JSONObject toJson(String jString){ 
    System.out.println("I've got"+jString+"*"); 

    try { 
     return new JSONObject(jString); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     System.out.println("Error while converting to JSONObject"); 
    } 

    return null; 
} 

修改后:

public JSONObject toJson(String jString){ 
    System.out.println("I've got"+jString+"*"); 

    try { 
     return new JSONArray(jString); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     System.out.println("Error while converting to JSONObject"); 
    } 

    return null; 
} 
+0

看看你正在返回的代码JSONArray,但方法retun类型是JSONObject? –

+0

谢谢;有用; – user1411688

2

here您的JSON只包含JsonArray列表如此只是将您的String转换为JSONArray而不是JSONObject为:

public JSONArray toJson(String jString){ 
    System.out.println("I've got"+jString+"*"); 

    try { 
     return new JSONArray(jString); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     System.out.println("Error while converting to JSONArray"); 
    } 

    return null; 
} 
+0

谢谢你;有用; – user1411688