Java 转换字符串时org.json.json.typeMismatch

Java 转换字符串时org.json.json.typeMismatch,java,android,json,Java,Android,Json,我正在尝试在Android应用程序中转换以下JSON: [ { "patient_id": "16", "patient_firstname": "Ion", "patient_name": "Vasilescu", "location": "Cardiologie, Salon 4, Pat 2" }, { "patient_id": "22", "patient_first

我正在尝试在Android应用程序中转换以下JSON:

[
    {
        "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"
    }
]
我已经通读了类似的问题和答案,但在我的例子中,我没有看到任何语法问题。我已经用检查过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;
}

有人对如何消除我的错误有什么建议吗?或者如何实施更好的解决方案?谢谢。

将JSONObject替换为JSONArray,因为它是一个数组

您得到的结果是JSon数组而不是JSon字符串,所以请尝试更改SLA

您的代码:

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;
}
查看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;
}

非常好地解释了教程:你得到的错误是什么?请发布完整的堆栈跟踪。看看你的代码,你返回的是JSONArray,但方法retun类型是JSONObject?