phpnerd
phpnerd

Reputation: 926

How to extract values from JSONObject in android

1.I am having json object like this how can i get the access to all values in android
2.before anyone down voting that i want to say i have searched stackoverflow for similar examples but those examples contains JSONObject and then JSONArray
3.Here in my case everything is JSONObject so i'm little bit confused

{
"1":
{"sno":"10","latitude":"31.249441437085455","longitude":"75.70003598928452"},

"2":
{"sno":"11","latitude":"31.249398442090207","longitude":"75.70003397762775"}
}

This is how i made it to JSONObject
1.Below code returned me output like that which is all JSONObject
2.Is there any way to make "1" and "2" as JSONArray ?

$select_rows = "select sno,latitude,longitude from activities where username='$username'";
if ($result = mysql_query($select_rows)) {

$num_of_fields = mysql_num_fields($result);
$num_of_rows = mysql_num_rows($result);

 $i = 0;

    $j = 1;

    while ($retrieved = mysql_fetch_array($result)) {

        for ($i = 0; $i < $num_of_fields; $i++) {

            $field_name = mysql_field_name($result, $i);

            $object[$j][$field_name] = $retrieved[$field_name];
        }
        $j++;
    }
    echo json_encode($object);
}

Upvotes: 3

Views: 16233

Answers (3)

Libin
Libin

Reputation: 17085

Better create a valid JSONArray to make things easier. When you create the JSON string , don't append the index. I believe your are reading the data from sqlite and generating the JSON string.

Also change the outer { (curly brace) to [ (square bracket) to represent as Array element. So your json string will be like this

[
{
    "sno": "10",
    "latitude": "31.249441437085455",
    "longitude": "75.70003598928452"
},
{
    "sno": "11",
    "latitude": "31.249398442090207",
    "longitude": "75.70003397762775"
}
]

Then , you can simply get its as JSONArray

JSONArray jsonArray = new JSONArray(jsonString);

And then read each element in array item

 for(int index = 0;index < jsonArray.length(); index++) {
    JSONObject jsonObject = jsonArray.getJSONObject(index);
 }

Upvotes: 5

shabeer
shabeer

Reputation: 143

Hope this may help you

JSONObject jsonObject=new JSONObject(result);

            jsonObject=jsonObject.getJSONObject("1");

            Double lat=jsonObject.getDouble("latitude");




            Toast.makeText(getBaseContext(),""+ lat, Toast.LENGTH_LONG).show();

Upvotes: 7

Matt O
Matt O

Reputation: 1346

To get one of your inner JSONObject elements, you'll need to get it from the outer one using getJSONObject(String key).

Sample code:

JSONObject item1 = myJson.getJSONObject("1");
//item1 now contains {sno:10,latitude:31.2...etc}
//now you can get the individual values out of the resulting JSON Object
//for example, getting the latitude
double lat = item1.getDouble("latitude");

Upvotes: 1

Related Questions