I am trying to parse a Json response from my webservice. I receive this string from my web server.
{"lon0":"30.13689","lat0":"-96.3331183333333"}{"lon1":"30.136965","lat1":"-96.33252"}{"lon2":"30.1370383333333","lat2":"-96.3319233333333"}
I place it in to a string called jsonStr..
then I place it into an object. And get strings that I need.
JSONObject jsonObj = new JSONObject(jsonStr);//place it into an object
String longitudecord = jsonObj.getString("lon0");//retrieve the lon0
String latitudecord = jsonObj.getString("lat0");
When I try this code above I get the proper longitudecord being 30.13689, and the proper latitudecord being -96.3331183333333.
but when I run this
String longitudecord = jsonObj.getString("lon1");
String latitudecord = jsonObj.getString("lat1");
I don’t get the correct longitude and latitude. It throws an exception. So I don’t think im trying to get “lon1” and “lat1” correctly.
Can anyone help me with this?
***UPDATE*******
my php code snippet…
$counter = 0;
// read them back
$result = mysql_query( "SELECT * FROM locations" );
while( $data = mysql_fetch_assoc($result) ) {
$latFromDb = $data['latitude'];
$longFromDb = $data['longitude'];
$variable = array( 'lon'.$counter => "$longFromDb", 'lat'.$counter => "$latFromDb" );
// One JSON for both variables
echo json_encode($variable);
$counter++;
}
How could I return the proper jSon format
It looks like you’re returning 3 separate results. So, some possibilities…
Form the string into a JSONArray, and parse that…
JSONArray jsonObj = new JSONArray("["+jsonStr.replaceAll("}{","},{")+"]");Then iterate through each child of the array to get the lat/long.
Split the returned String into separate result strings, and parse them individually. Maybe something like this…
String[] results = jsonStr.replaceAll("}{","}}{{").split("}{");Note that we replaceAll first so we can keep the
}and{at the start/end of each result.The better thing would be to fix your PHP server code. You basically just need a
[at the start, an]at the end, and,between each result. I think something like this might do it (please fix the syntax for me – i’m not a PHP coder).Once you’ve got that, you should just be able to say
new JSONArray(serverResult)and it’ll parse all of your results into a JSON Array that you can iterate through.