Reputation: 251
how I can convert data returned from server from this format
[{"Food":"orange","Protein":"52","Water":"52","Magnesium":"12","Phosphorus":"12","Sodium":"12.5","Zinc":"45","Vit_C":"12","Fat_Sat":"12","Fat_Mono":"45","Vit_B12":"45","Calcium":"45","Calories":"4565","Fiber":"12","Cholesterole":"12","Potassium":"12","Sugar_Tot":"55","Iron":"45","Folic_Acid":"55","carbohydrates":"55","Vit_K":"5","Serving_Size":"\u062d\u0628\u0629"}]
to this
"[{\"Food\":\"\\u062a\\u0641\\u0627\\u062d \\u0628\\u062f\\u0648\\u0646 \\u0627\\u0644\\u0642\\u0634\\u0631\\u0629\",\"Protein\":\"0.27\",\"Water\":\"86.67\",\"Magnesium\":\"4\",\"Phosphorus\":\"11\",\"Sodium\":\"0\",\"Zinc\":\"0.05\",\"Vit_C\":\"4\",\"Fat_Sat\":\"0\",\"Fat_Mono\":\"0\",\"Vit_B12\":\"0\",\"Calcium\":\"5\",\"Calories\":\"48\",\"Fiber\":\"1\",\"Cholesterole\":\"0\",\"Potassium\":\"90\",\"Sugar_Tot\":\"10.1\",\"Iron\":\"0.07\",\"Folic_Acid\":\"0\",\"carbohydrates\":\"13\",\"Vit_K\":\"0.6\"}]";
because the first format cause exception in emulator 2.2 ( parssingorg.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray)
this is part of my code :
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
sb = new StringBuilder();
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line);}
is.close();
result =sb.toString();
// result = result.replace('\"', '\'').trim();
Log.d("",result);
}
catch(Exception e){
Log.e("log_tag", "error" + e.toString());
}
Log.d("",result);
try{
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
if(json_data!=null )
{
foodName=json_data.getString("Food");
Description=json_data.getInt("Calories");
item.setName(foodName);
item.setDescription(10);
item.setSelected(false);
MealActivity.foodList.add(item);
item=new ItemInList();
Upvotes: 0
Views: 370
Reputation: 1438
I assume that there is a ]
at the end of the line
The data returned from server is a JSON Array with 1 JsonObject.
You can parse it with:
JSONArray jArray = new JSONArray(result);
String foodName = jArray.getJSONObject(0).getString("Food");
And so on..
Upvotes: 0
Reputation: 280
The returned JSON file is not complete, it's missing the Square brackets at the end to close the array.
if this JSON aways returns, then manually add the close Square brackets at the end
// your code
result =sb.toString();
if(!result.endsWith("]")) {
result = result + "]";
}
// continue the rest of the cod
also you can use this code to check if it's a valid JSON check if file is json, java
I hope this helps
Upvotes: 1