user1411688
user1411688

Reputation: 31

org.json.JSON.typeMismatch when converting a String

I'm trying to convert the following JSON in a Android app:

[
    {
        "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"
    }
]

I've read through simillar problems and answers but in my case I don't see any syntax problems. I've checked the JSON with JSONLint and it validated successfully.

My java code is as follows:

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

Does anybody have advice on how to get rid of my error? Or on how to implement a better solution ? Thanks.

Upvotes: 2

Views: 6538

Answers (3)

sravan
sravan

Reputation: 5333

You are getting result as a JSon Array not JSon string so try to change slass

Your code:

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

After modification:

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

Upvotes: 3

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

See here your json contain only JsonArray List so just convert your String to JSONArray instead of JSONObject as:

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

Upvotes: 2

nithinreddy
nithinreddy

Reputation: 6197

Replace JSONObject to JSONArray, since its an array!

Upvotes: 4

Related Questions