Reputation: 31
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
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
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