1

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

5
  • 1
    Please update your title to a more descriptive one (every usable JSON string has more than "{}"...) Commented May 3, 2012 at 14:04
  • 3
    I'd recommend to form json string as array of objects [{},{},...] Commented May 3, 2012 at 14:05
  • Is that valid JSON string? I'm not sure... Commented May 3, 2012 at 14:06
  • {}{} is no valid JSON. See json.org Commented May 3, 2012 at 14:09
  • Not valid JSON. It looks like the user has asked for 4 separate lat/logs, and they are appended together into a single string rather than forming them into an array. Commented May 3, 2012 at 14:14

4 Answers 4

4

It looks like you're returning 3 separate results. So, some possibilities...

  1. 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.

  2. 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).

    $counter = 0;
// read them back
$result = mysql_query( "SELECT * FROM locations" );
echo '[';
while( $data = mysql_fetch_assoc($result) ) {
if (&counter >= 1){
  echo ',';
}
$latFromDb = $data['latitude'];
$longFromDb = $data['longitude'];
$variable = array( 'lon'.$counter => "$longFromDb", 'lat'.$counter => "$latFromDb" );
    // One JSON for both variables
echo json_encode($variable);
$counter++;
}
echo ']';

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I tried the second one, and the first and I get this line upon debugging '05-03 14:45:10.452: E/AndroidRuntime(476): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_RULE_SYNTAX near index 1: }{'
Apologies, you'll need to escape the characters by doing this... replaceAll("\}\{","}}{{"). I have edited my answer.
With your latest update in Eclipse its saying: Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )
Bugger, I didn't think the { and } needed to be escaped, so was surprised by your original comment. Not really sure what's wrong with it :-( . I see you've edited your original question with PHP code - it would definitely be the right approach to fix it there!
I've edited my answer to include PHP changes that should make it JSON-proper.
|
3

Your jsonStr isn't valid, its missing brackets and commas between each record. Use:

[
    {
        "lon0": "30.13689",
        "lat0": "-96.3331183333333"
    },
    {
        "lon1": "30.136965",
        "lat1": "-96.33252"
    },
    {
        "lon2": "30.1370383333333",
        "lat2": "-96.3319233333333"
    }
]

PHP:

$sth = mysql_query("SELECT latitude,longitude FROM locations");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows[] = $r;
}
echo json_encode($rows);

This should output the correct format.

2 Comments

Could you see my ****Update****, my php code is there. I am trying to figure out how to display them like you have said.
Take a look a look at this link. You need to encode the string as an array of lon and lat objects.
1

JSONObject will only take the first JSON that figures on the string. By doing this:

JSONObject jsonObj = new JSONObject(jsonStr);

your object will end up containing the firs json:

{"lon0":"30.13689","lat0":"-96.3331183333333"}

So when you try to obtain data regarding another json object it won't find the key you specify. You'll have to parse the string in some way, I think doing something like this might work:

String separatedJsons= jsonStr.replace("}{", "}###{");
String jsons[] = separatedJsons.split("###");

That way you end up with an array of Strings, each one with the individual jsons. You can create your JSONObjects with each one later.

Comments

0

I'm not sure that webservice response is properly formatted JSON, which could be the issue?

If you have the means to edit the string being generated by your app you could try something like the following:

[
{"lon0":"30.13689","lat0":"-96.3331183333333"},
{"lon1":"30.136965","lat1":"-96.33252"},
{"lon2":"30.1370383333333","lat2":"-96.3319233333333"}
]

1 Comment

Could you see my Update, my php code is there. I am trying to figure out how to display them like you have said.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.