How to parse the JSON in android? - android

"carMake": {
"Tata": [
"FIAT",
"INDICA VISTA",
"INDIGO XL"
],
"Hyndai": [
"SANTRO Xing",
"I10",
"I20",
"ACCENT",
"SONATA"
]
},
I just need to parse this part in my response. I tried with map but I am not getting it solved.

use gson.
http://code.google.com/p/google-gson/

You could try using a JSON Object parser.
Here's a link to an example http://www.jondev.net/articles/Android_JSON_Parser_Example

See the bellow example.
The response string is like this
String jsonStr = '{"menu": {' +
'"id": "file",' +
'"value": "File",' +
'"popup": {' +
'"menuitem": [' +
'{"value": "New", "onclick": "CreateNewDoc()"},' +
'{"value": "Open", "onclick": "OpenDoc()"},' +
'{"value": "Close", "onclick": "CloseDoc()"}' +
']' +
'}' +
'}}';
use the bellow code to parse the json String
// grabbing the menu object
JSONObject jsonObf=new JSONObject(jsonStr);
JSONObject menu = jsonObj.getJSONObject("menu");
// these 2 are strings
String id = menu.getString("id");
String value = menu.getString("value");
// the popop is another JSON object
JSONObject popup = menu.getJSONObject("popup");
// using JSONArray to grab the menuitems from under popop
JSONArray menuitemArr = popupObject.getJSONArray("menuitem");
// lets loop through the JSONArray and get all the items
for (int i = 0; i < menuitemArr.length(); i++) {
// printing the values to the logcat
Log.v(menuitemArr.getJSONObject(i).getString("value").toString());
Log.v(menuitemArr.getJSONObject(i).getString("onclick");
}
In your case, do the simple modifications to achieve the solution.

Related

Missing keys in JSON format

I am trying to parse a JSON string in Android which is dynamical. It is a very simple JSON structure. Similar to the following:
{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5
}
But sometimes I don't get some keys. For example, the key "b" could be missing. Then my code generates a JSONParser Exception. And the further JSON string could not parsed.
So is there any way to ignore missing keys? I tried optString(); but that only works in String case, what about JSONObject and JSONArray? optJSONArray() and optJSONObject() don't work.
Any idea or solution?
I think the easiest way is to use
GSON!
You simply create a plain old java object (POJO) representing the data you want and let GSON do the rest. If the value doesn't exist in the json string, it'll be set to the "default" for that type (usally null, but is 0 for ints, false for booleans etc...)
To include in your Android Studio project:
compile 'com.google.code.gson:gson:2.2.4'
Also take a look at this page, with particular attention to the "Object Examples" heading for how to use GSON.
You can find dynamic key using belo
String jsonString = "{ \"a\": 1, \"b\": 2, \"c\": 3, \"d\": 4, \"e\": 5 }";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject issueObj = new JSONObject(jsonString);
Iterator iterator = issueObj.keys();
while(iterator.hasNext()){
String key = (String)iterator.next();
Integer value = (Integer) issueObj.get(key);
Log.d(TAG,"value: "+value);
}
} catch (JSONException e) {
e.printStackTrace();
}
Or you can use GSON.
You can try convert that JSONObject to a Map using GSON, like the following:
String json1 = "{\n" +
" \"a\": 1,\n" +
" \"b\": 2,\n" +
" \"c\": 3,\n" +
" \"d\": 4,\n" +
" \"e\": 5\n" +
"}";
Gson gson1 = new Gson();
Type type1 = new TypeToken<Map<String, Integer>>(){}.getType();
Map<String, Integer> myMap1 = gson1.fromJson(json1, type1);
In your build.gradle file:
compile 'com.google.code.gson:gson:2.3.1'

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);
}
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();
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);
}
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");

How to get a value from JSON Object by a key?

How to get the value by key in a JSON object? I had used following code but it receives "org.json.JSONException". Advance thanks for any help.
String resultJSON = "{Data:[{\"AreaID\":\"13\", \"Phone\":\"654321\", \"RegionName\":\"Sivakasi\"}, {\"AreaID\":\"14\", \"Phone\":\"12345\", \"RegionName\":\"ANJAC\"}]}";
JSONObject jObject = new JSONObject(resultJSON);
JSONObject jsonObject = jObject.getJSONObject("Data");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jsonObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jsonObject.getString(key);
map.put(key,value);
Log.d("Key Value","key: "+key+" Value: "+value);
}
Logcat details
org.json.JSONException: Value [{"AreaID":"13","Phone":"654321","RegionName":"Sivakasi"},{"AreaID":"14","Phone":"12345","RegionName":"ANJAC"}] at Data of type org.json.JSONArray cannot be converted to JSONObject
The structure of your JSON is wrong, you should use a Key for the second JSONObject , like this:
{
Data: {
\"AreaID\": \"13\",
\"Phone\": \"654321\",
\"RegionName\": \"Sivakasi\"
},
\"KEY\": {
\"AreaID\": \"14\",
\"Phone\": \"12345\",
\"RegionName\": \"ANJAC\"
}
}
Or the DATA should be a JSONArray ( surrounded by [] ) like this :
{
Data: [
{
\"AreaID\": \"13\",
\"Phone\": \"654321\",
\"RegionName\": \"Sivakasi\"
},
{
\"AreaID\": \"14\",
\"Phone\": \"12345\",
\"RegionName\": \"ANJAC\"
}
]
}
NOTE : you can check if your json is valid or not here
Personnaly , i prefer the second way ( Using JSONArray) , because the data inside has the same attributes (AreaID, Phone, REgionName). To parse data in this case , your code should be someting like this :
String resultJSON = "{Data:[{\"AreaID\":\"13\", \"Phone\":\"654321\", \"RegionName\":\"Sivakasi\"}, {\"AreaID\":\"14\", \"Phone\":\"12345\", \"RegionName\":\"ANJAC\"}]}";
JSONObject jsonRoot = new JSONObject(resultJSON);
JSONArray jsonData = jsonRoot.getJSONArray("Data");
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonOBject = jsonData.getJSONObject(i);
Log.d(TAG, "json ("+i+") = "+jsonOBject.toString());
// do what you want with your JSONObject , i.e :add it to an ArrayList of paresed result
String areaID = jsonOBject.getString("AreaID");
int phoneNumber = jsonOBject.getInt("Phone");
String regionName = jsonOBject.getString("RegionName");
}
This is invalid JSON format. Before you convert your string to JSON object format, be sure about it's valid or not.
Please check validity of your JSON.
Hope it may help.

Android create a JSON array of JSON Objects

hi does anyone know how to create a Array that contains objects that in each objects contain several objects? i just can't seem to get my head round it
the structure should look like this
Array{[object]{subobject,subobject}
[object]{subobject,subobject}
}
heres what i have so far
JSONObject obj = new JSONObject(json2);
JSONObject objData = obj.getJSONObject("data");
fixturesArray = objData.getJSONArray("fixtures");
JSONArray FixArray = new JSONArray();
for(int t = 0; t < fixturesArray.length(); t++){
JSONObject fixObj = fixturesArray.getJSONObject(t);
String Matchdate = fixObj.getString("matchdate");
JSONObject DateObj = DateObj.put(Matchdate, DateObj);
heres my JSON essentially what i have if is a feed of fixtures i need to order them in to arrays of dates
{
"code":200,
"error":null,
"data":{
"fixtures":[
{
"kickoff":"15:00:00",
"matchdate":"2012-07-28",
"homescore":null,
"awayscore":null,
"attendance":null,
"homepens":null,
"awaypens":null,
"division_id":"5059",
"division":"Testing 1",
"comp":"LGE",
"location":null,
"fixture_note":null,
"hometeam_id":"64930",
"hometeam":"Team 1",
"awayteam_id":"64931",
"awayteam":"Team 2"
}, {
"kickoff":"15:00:00",
"matchdate":"2012-07-28",
"homescore":null,
"awayscore":null,
"attendance":null,
"homepens":null,
"awaypens":null,
"division_id":"5059",
"division":"Testing 1",
"comp":"LGE",
"location":null,
"fixture_note":null,
"hometeam_id":"64930",
"hometeam":"Team 1",
"awayteam_id":"64931",
"awayteam":"Team 2"
}
]
}
}
Do you mean that?:
JSONObject obj = new JSONObject();
obj.put("x", "1");
JSONObject parent_object = new JSONObject();
parent_object.put("child", obj);
JSONArray array = new JSONArray(parent_object.toString());
JSON String
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea"}
]
}
Here below I am fetching country details
JSONObject json = new JSONObject(jsonstring);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
What I would suggest to do is to use JackSON JSON Parser library http://jackson.codehaus.org/ Then you can create a Class with the same fields as the JSON son the mapping from JSON To class will be direct.
So once you have all the items from JSON into a List of class you can order by dates or manipulate data as you want. Imagine that src is a String containing the JSON text. With JackSON lib you just need to do this.
ObjectMapper mapper = new ObjectMapper();
List<Fixture> result = mapper.readValue(src, new TypeReference<List<Fixture>>() { });
Here are two pieces of JSON which fit your description which is "Array that contains objects that in each objects contain several objects". The first method uses Arrays inside Objects. The other one uses Objects in Objects.
Method 1
[ { "name" : "first object in array" , "inner array" : [ { <object> } , { <object> } ] }
, { "name" : "second object in array" , "inner array" : [ { <object> } , { <object> } ] } ]
To parse the above you need two nested for loops (or something recursive).
Method 2
[ { "name" : "first object in array" , "first inner object" : { <object> } , "second inner object" : { <object> } } , <etc.> ] } ]
The second method can be parsed with a single for loop because you know in advance the number of inner objects to expect.

how to decode json in android

this is my json data
[{"FeedbackId":"1","Phoneid":"9774d56d682e549c","feedbackdate":"2011\/9 \/24","GuestName":"sdf","Address":"sdf","Phone":"456","Email":"sdf","suggestion":"sdf","grievances":"sdf","visitAgain":"0","purposeofvisit":"sdf","flag":"1"},{"FeedbackId":"2","Phoneid":"9774d56d682e549c","feedbackdate":"","GuestName":"sdf","Address":"sdf","Phone":"456","Email":"sdf","suggestion":"sdf","grievances":"sdf","visitAgain":"0","purposeofvisit":"sdf","flag":"1"},{"FeedbackId":"3","Phoneid":"9774d56d682e549c","feedbackdate":"","GuestName":"sdf","Address":"sdf","Phone":"456","Email":"sdf","suggestion":"sdf","grievances":"sdf","visitAgain":"0","purposeofvisit":"sdf","flag":"1"},{"FeedbackId":"4","Phoneid":"9774d56d682e549c","feedbackdate":"2011\/9 \/24","GuestName":"sdf","Address":"dsf","Phone":"456","Email":"sdf","suggestion":"sf","grievances":"sdf","visitAgain":"0","purposeofvisit":"sdf","flag":"1"},{"FeedbackId":"5","Phoneid":"9774d56d682e549c","feedbackdate":"2011\/9 \/24","GuestName":"sdf","Address":"dsf","Phone":"456","Email":"sdf","suggestion":"sf","grievances":"sdf","visitAgain":"0","purposeofvisit":"sdf","flag":"1"},{"FeedbackId":"6","Phoneid":"9774d56d682e549c","feedbackdate":"","GuestName":"xcv","Address":"xcv","Phone":"89","Email":"xcv","suggestion":"xcv","grievances":"xcv","visitAgain":"1","purposeofvisit":"","flag":"1"},{"FeedbackId":"7","Phoneid":"9774d56d682e549c","feedbackdate":"","GuestName":"gfhj","Address":"ghj6678","Phone":"678","Email":"ghjgh","suggestion":"678fgh","grievances":"fgh","visitAgain":"0","purposeofvisit":"sdf","flag":"1"}]
how to decode this?
You should be able to decode using the org.json package. From here:
String json = "{"
+ " \"query\": \"Pizza\", "
+ " \"locations\": [ 94043, 90210 ] "
+ "}";
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
String query = object.getString("query");
JSONArray locations = object.getJSONArray("locations");
Just use your own JSON instead of theirs.

Categories

Resources