-1

I have JSON response:

 {"error":100,"result":"{\"distance\":2.4,\"duration\":5,\"price\":0}"}

From this response I want to get a "distance" value for example. How to do it?

I tried to do like this:

 String distance = String.valueOf(finalResponseDataJOSNObject.getDouble("distance"));

but string value is null. Any ideas?

UPDATE:

Finally we discovered that it was back-end issue and we fixed it. No additional operations like JSONObject conversation to String, special character removal, etc. was necessary.

Simply:

String distance =  
String.valueOf(finalResponseDataJOSNObject.getJSONObject("result").getDouble("di‌​stance"));
user2999943
  • 2,419
  • 3
  • 22
  • 34

4 Answers4

1

The distance is in a JSONObject under result only. So you have to getJSONObject("result").getDouble("distance").

learner
  • 3,092
  • 2
  • 21
  • 33
Heinrisch
  • 5,835
  • 4
  • 33
  • 43
  • I tried like this: String distance = String.valueOf(finalResponseDataJOSNObject.getJSONObject("result").getDouble("distance")); my string still is null. – user2999943 Aug 08 '14 at 13:07
  • Then your finalResponseDataJOSNObject is not as you described. What do you get when printing finalResponseDataJOSNObject.getJSONObject("result")? or just finalResponseDataJOSNObject – Heinrisch Aug 08 '14 at 13:09
1

Try this...

String json = "{\"error\":100,\"result\":{\"distance\":2.4,\"duration\":5,\"price\":0}}";
try {
    JSONObject jsonObject = new JSONObject(json);
    double distance = jsonObject.getJSONObject("result").getDouble(
            "distance");
    Log.i("DISTANCE", String.valueOf(distance));
} catch (JSONException e) {
    e.printStackTrace();
}
Jagadesh Seeram
  • 2,630
  • 1
  • 16
  • 29
1

You can do this in following way: Remove special character from json string and convert back to json object and process it accordingly:

String json = "{\"error\":100,\"result\":{\"distance\":2.4,\"duration\":5,\"price\":0}}";
try{

    JSONObject jsonObject = new JSONObject(json.replaceAll("\"", ""));

    JSONObject jsonObject2=jsonObject.getJSONObject("result");

    String distance=jsonObject2.getString("distance");

    double convertedDistance=Double.valueOf(distance);

    Log.i("DistanceInformation", "My Distance from json is="+distance);



}catch(JSONException e)
{
    e.printStackTrace();
}
DeepakPanwar
  • 1,389
  • 14
  • 22
0

Thanks for you all who responded.

Finally we discovered that it was back-end issue and we fixed it. No additional operations like JSONObject conversation to String, special character removal, etc. was necessary.

Simply:

String distance =  
String.valueOf(finalResponseDataJOSNObject.getJSONObject("result").getDouble("di‌​stance"));
user2999943
  • 2,419
  • 3
  • 22
  • 34