Hey guys this is the first time I am doing JSON and I have gotten the json from the server. Now my only question is how do I take the data.
The JSON includes
[
{
"name": "Joe Smith",
"employeeId":1,
"company": "ABC",
"phone": {
"work": "555-555-5555",
"home": "666-666-6666",
"mobile": "777-777-7777"
}
},
{
"name": "Does Smith",
"employeeId":2,
"company": "XYZ",
"phone": {
"work": "111-111-1111",
"home": "222-222-2222",
"mobile": "333-333-3333"
}
}
]
jsonData is my string of the JSON
Currently I have:
JSONObject json = new JSONOBject(jsonData);
JSONObject data = json.getJSONObject(*******)
JSONArray phones = data.getJSONArray("phone");
not sure what to put on the second line. Also, what is the best way to group the information.
Please make it easy to understand, not exactly a professional yet haha
Thanks!
Your first line is wrong because current string is JSONArray of JSONObject's so get data from current string as:
JSONArray json = new JSONArray(jsonData);
for(int i=0;i<json.length();i++){
JSONObject data = json.getJSONObject(i);
// get name,employeeId,... from data
String str_name=data.optString("work");
//...
JSONObject jsonobjphones = data.getJSONObject("phone");
// get work from phone JSONObject
String str_work=jsonobjphones.optString("work");
//....
}
Try this
List list=new ArrayList();
JSONObject jObject = new JSONObject(str_response_starter);
JSONArray json_array_item_id = jObject.getJSONArray("itemid");
System.out.println("json array item id"+json_array_item_id);
JSONArray json_array_item_name = jObject.getJSONArray("itemname");
System.out.println("json array item name"+json_array_item_name);
JSONArray json_array_item_type = jObject.getJSONArray("type");
System.out.println("json array item type"+json_array_item_type);
JSONArray json_array_item_cost = jObject.getJSONArray("cost");
System.out.println("json array item cost"+json_array_item_cost);
Now
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size());
String k, v;
Iterator<String> itKeys = kvPairs.keySet().iterator();
while (itKeys.hasNext()) {
k = itKeys.next();
System.out.println(" value of k"+k);
v = kvPairs.get(k);
System.out.println(" value of v"+v);
In JSON, [] represents JSONArray, {} represents JSONObject. In your JSON string, it starts with [, so you need to start with JSONArray:
JSONArray people = new JSONArray(jsonData);
And then you'll notice that each person is a JSONObject, so now you need to loop them in order to get their information:
for(int i=0;i<people.length();i++){
JSONObject person = people.getJSONObject(i);
JSONObject phones = person.getJSONObject("phone"); //phone is also a JSONObject, because it starts with '{'
String workPhone = phones.get("work");
}
Related
i'm confused on how to parse this JSON.
So far this is my approach. Also please tell me the right approach for parsing JSON in Android
JSON:
{
"latitude":37.8267,
"longitude":-122.423,
"timezone":"America/Los_Angeles",
"offset":-7,
"currently":{
"time":1443322196,
"summary":"Partly Cloudy",
"icon":"partly-cloudy-night",
"nearestStormDistance":13,
"nearestStormBearing":77,
"precipIntensity":0,
"precipProbability":0,
"temperature":63.94,
"apparentTemperature":63.94,
"dewPoint":55.46,
"humidity":0.74,
"windSpeed":8.59,
"windBearing":277,
"visibility":8.51,
"cloudCover":0.44,
"pressure":1010.39,
"ozone":261.48
},
"minutely":{
"summary":"Partly cloudy for the hour.",
"icon":"partly-cloudy-night",
"data":[
{
"time":1443322140,
"precipIntensity":0,
"precipProbability":0
},
}
Now the "currently" object is being parsed but when i try to parse "minutely" object it shows no value in Logcat
Here's my code:
JSONObject forecast = new JSONObject(jsonData);
JSONArray summary = new JSONArray(jsonData);
String timezone = forecast.getString("timezone");
String city = getLocationName(forecast.getDouble("latitude"), forecast.getDouble("longitude"));
JSONObject currently = forecast.getJSONObject("currently");
JSONArray hour = summary.getJSONArray("minutely");
for (int i = 0; i < hour.length(); i++) {
JSONObject jsonObject = hour.getJSONObject(i);
String summary = jsonObject.getString("summary");
}
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setTemp(currently.getDouble("temperature"));
currentWeather.setTimezone(timezone);
currentWeather.setLocation(city);
Based on the response from the endpoint url that you added in comments the parsing would look like this
JSONObject forecast = new JSONObject(jsonData);
double latitude = forecast.getDouble("latitude");
double longitude= forecast.getDouble("longitude");
String timezone = forecast.getString("timezone");
JSONObject jsonObjCurrently= forecast.getJSONObject("currently");
//parse string, long and double objects within jsonObjCurrently accordingly
JSONObject jsonObjMinutely= forecast.getJSONObject("minutely");
String summary= jsonObjMinutely.getString("summary");
String icon= jsonObjMinutely.getString("icon");
JSONArray jsonArrayMinutelyData = jsonObjMinutely.getJSONArray("data");
for(int i=0; i<jsonArrayMinutelyData .length(); i++){
JSONObject tempData = jsonArrayMinutelyData.get(i);
long time = tempData.getLong("time");
//parse the remaining object pairs.
}
JSONObject jsonObjHourly= forecast.getJSONObject("hourly");
//similar to minutely parsing. Only has more and different data
JSONObject jsonObjDaily= forecast.getJSONObject("daily");
//similar to hourly parsing.
JSONObject jsonObjFlags= forecast.getJSONObject("flags");
//It has 5 array and 1 string object so parse accordingly.
I have added the parsing logic please save the data accordingly and use it.
You may parse the minutely at wrong path. see code below (tested).
try {
// jsonString from https://api.forecast.io/forecast/8162461ea194cb97c80209d6edf4df94/37.8267,-122.423
String jsonString = "";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject minutely = jsonObject.getJSONObject("minutely");
Log.d("JSON", "minutely: " + minutely);
String summary = minutely.getString("summary");
Log.d("JSON", "summary: " + summary);
JSONArray datas = minutely.getJSONArray("data");
for (int i = 0; i < datas.length(); i++) {
JSONObject data = datas.getJSONObject(i);
Log.d("JSON", "data # index" + i + ": " + data);
}
} catch (JSONException e) {
e.printStackTrace();
}
output:
D/JSON ( 1590): minutely: {"summary":"Partly cloudy for the hour.","icon":"partly-cloudy-night","data":....
D/JSON ( 1590): summary: Partly cloudy for the hour.
D/JSON ( 1590): data # index0: {"time":1443331140,"precipIntensity":0,"precipProbability":0}
D/JSON ( 1590): data # index1: {"time":1443331200,"precipIntensity":0,"precipProbability":0}
....
This is not a valid json.
You can check your logcat for the exception thrown.
If the exception has been caught, try and print stack trace. That will help you know where the problem is.
i check your json again and it should be one of two cases
the first is like
{
"latitude":37.8267,
"longitude":-122.423,
"timezone":"America/Los_Angeles",
"offset":-7,
"currently":{
"time":1443322196,
"summary":"Partly Cloudy",
"icon":"partly-cloudy-night",
"nearestStormDistance":13,
"nearestStormBearing":77,
"precipIntensity":0,
"precipProbability":0,
"temperature":63.94,
"apparentTemperature":63.94,
"dewPoint":55.46,
"humidity":0.74,
"windSpeed":8.59,
"windBearing":277,
"visibility":8.51,
"cloudCover":0.44,
"pressure":1010.39,
"ozone":261.48
},
"minutely":{
"summary":"Partly cloudy for the hour.",
"icon":"partly-cloudy-night",
"data":[
{
"time":1443322140,
"precipIntensity":0,
"precipProbability":0
},
}
and the solution will be look like.
JSONObject minutely = forecast.getJSONObject("minutely");
second it like
[
{
"latitude": 37.8267,
"longitude": -122.423,
"timezone": "America/Los_Angeles",
"offset": -7,
"currently": {
"time": 1443322196,
"summary": "Partly Cloudy",
"icon": "partly-cloudy-night",
"nearestStormDistance": 13,
"nearestStormBearing": 77,
"precipIntensity": 0,
"precipProbability": 0,
"temperature": 63.94,
"apparentTemperature": 63.94,
"dewPoint": 55.46,
"humidity": 0.74,
"windSpeed": 8.59,
"windBearing": 277,
"visibility": 8.51,
"cloudCover": 0.44,
"pressure": 1010.39,
"ozone": 261.48
},
"minutely": {
"summary": "Partly cloudy for the hour.",
"icon": "partly-cloudy-night",
"data": [
{
"time": 1443322140,
"precipIntensity": 0,
"precipProbability": 0
}
]
}
}
]
and solution will be that you should change your forecast object to be JsonArray.
You can test the validation of your json here
Minutely is not JSONArray its JSONObject.
Try this:-
JSONObject forecast = new JSONObject(jsonData);
JSONObject jsonObjMinutely= forecast.getJSONObject("minutely");
String summary = jsonObjMinutely.getString("summary");
Your minutely is invalid JSON..
Let's take a look at that closer:
"minutely":{
"summary":"Partly cloudy for the hour.",
"icon":"partly-cloudy-night",
"data":[
{
"time":1443322140,
"precipIntensity":0,
"precipProbability":0
},
It doesn't have a closing bracket for both the minutely's JSONObject and data's JSONArray. Also, it has a comma where "data" array actually contains one element.
Fixing those to:
"minutely":{
"summary":"Partly cloudy for the hour.",
"icon":"partly-cloudy-night",
"data":[
{
"time":1443322140,
"precipIntensity":0,
"precipProbability":0
} ]
}
Then your "minutely" object is now valid. This is first.
Then to get your "minutely"
...
JSONObject forecast = new JSONObject(jsonData);
JSONObject minutely = forecast.getJSONObject("minutely");
parsing json is very easy now with android studio. In android studio install plugin GSON then create model class and enter 'alt+insert' it will popup for generator then select GSONFormat and paste your json there you will get model class for your json. In activity where you get json response do this
Gson gson = new Gson();
YourModelClass object = gson.fromJson(jsonResponseObject.toString(), YourModelClass.class);
Here you succefully parsed json. Now its time to use your model class to get data whereever you want it
Please edit your code like below
JSONObject currently = forecast.getJSONObject("currently");
Double humidity = currently.getDouble("humidity");
Long time = currently.getLong("time");
String icon = currently.getString("icon");
Double precipChance = currently.getDouble("precipProbability");
Double temp = currently.getDouble("temperature");
String timezone = forecast.getString("timezone");
JSONObject minutely = forecast.getJSONObject("minutely");
Have a look at below link for complete example of Json Parsing
https://www.dropbox.com/s/q6cjifccbbw9nl1/JsonParsing.zip?dl=0
I am a beginner in android coding. I am working on an app which gets data from php web service in JSON format, but I am not able to correctly parse it.
JSON returned looks like this:
{
"posts": [
{
"post": {
"Id": "1",
"Title": "Captain America",
"Lang": "ENG"
}
}
]
}
Android code:
JSONObject job = new JSONObject(json);//json is the string returned by web service
jObj = job.getJSONArray("posts");
JSONObject c = jObj.getJSONObject(0);
String title = c.getString("Title");
But I get a JSON exception:No value for Title
I cant figure out whats going wrong.
You have
{ //JSONObject job = new JSONObject(json); ok
"posts": [ // jObj = job.getJSONArray("posts"); ok
{ // JSONObject c = jObj.getJSONObject(0) ok
"post": { // forgot about jsonobject post // missed JSONObject post = c.getJSONObject("post")
"Id": "1",
"Title": "Captain America",
Change to
JSONObject c = jObj.getJSONObject(0);
JSONObject post = c.getJSONObject("post");
String title = post.getString("Title");
JSONObject job = new JSONObject(json);//json is the string returned by web service
JSONArray jar=job.getJSONArray("posts");
for (int i=0;i<jar.length();i++)
{
job=jar.getJSONObject(i);
job=jat.getJSONObject("post");
title=job.optString("Title");
}
You forget to get "post" value
I am getting Json parsing
Here my java code
if(jsonstr!=null){
try{
JSONObject jsonResponse = new JSONObject(jsonstr);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonproduct = jsonResponse.optJSONArray("products");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonproduct.length();
for (int i = 0; i < lengthJsonArr; i++) {
JSONObject c = jsonproduct.getJSONObject(i);
itemcode.add(c.get("Code").toString());
item.add(c.get("Name").toString());
quantity.add("");
category.add("CategoryCode");
}
Error is
org.json.JSONException: Value [{"categories":[{......................all json}]
My json is Like
[ { categories{[ "a":"s" "b":"g"
},
{ "a":"s" "b":"g"
}
]},
product{[ "a":"s" "b":"g"
},
{ "a":"s" "b":"g"
}
]} ]
MY Json web service url
[webservice][1]
Please Help Me How I can fix this problem
Thanks In Advance
Try that:
replace products to categories
try{
JSONObject jsonResponse = new JSONObject(jsonstr);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonproduct = jsonResponse.optJSONArray("categories");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonproduct.length();
for (int i = 0; i < lengthJsonArr; i++) {
JSONObject c = jsonproduct.getJSONObject(i);
itemcode.add(c.get("Code").toString());
item.add(c.get("Name").toString());
quantity.add("");
category.add("CategoryCode");
}
try this,
if(jsonstr!=null){
try{
JSONArray jsonResponse = new JSONArray(jsonstr);
JSONObject jsonResponse = jsonResponse.get(0);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonproduct = jsonResponse.getJSONArray("products");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonproduct.length();
for (int i = 0; i < lengthJsonArr; i++) {
JSONObject c = jsonproduct.getJSONObject(i);
itemcode.add(c.get("Code").toString());
item.add(c.get("Name").toString());
quantity.add("");
category.add("CategoryCode");
}
Your JSON is not valid.
You can use a online tool for checking: http://json.parser.online.fr/
Link for the JSON Syntax: http://www.w3schools.com/json/json_syntax.asp
EDIT:
Ok, now we have your real JSON, it's correct.
What about replacing JSONObject by JSONArray. Because your JSON is a Array.
Your JSON is not valid.
Maybe you were going for something like this?
{
"categories": [
{
"a": "s",
"b": "g"
},
{
"a": "s",
"b": "g"
}
],
"product": [
{
"a": "s",
"b": "g"
},
{
"a": "s",
"b": "g"
}
]
}
its because the json you are using is not valid.
and the parsing you are doing is not valid too
here is a good link to start off with android json parsing
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
This happening because your json is start with the jsonArray then why you take the jsonObject for that
[
{
"categories": [
{
"Code": "1001",
"Name": "ROOM LINEN",
"ShortName": "ROLN",
"DivisionCode": "10",
"SequenceNo": "3"
you should try #akash moradiya's code a given ans he is pointing to right way.
Try this..
JSONArray jsonarray = new JSONArray(jsonstr);
JSONObject jsonResponse = jsonarray.getJSONObject(1);
JSONArray jsonproduct = jsonResponse.getJSONArray("products");
for (int i = 0; i < jsonproduct.length(); i++) {
JSONObject c = jsonproduct.getJSONObject(i);
itemcode.add(c.getString("Code"));
item.add(c.getString("Name"));
quantity.add("");
category.add("CategoryCode");
}
So I am receiving a JSON array in an httpresponse. The array consists of the following objects/variables.
{"sessid":"vxkEXkMBUmBByESRlvaxrxSaFTfhDqd8","session_name":"SESS88cdfb2f1c420898","user":{"uid":"60","name":"abc","theme":"","signature":"","signature_format":"filtered_html","created":"13082976","access":"1386287","login":1386211,"status":"1","timezone":null,"language":"","picture":null,"data":{"mimemail_textonly":0},"roles":{"2":"authenticated user","5":"centre user"},"field_centre_reference":{"und":[{"nid":"256"}]},"field_first_name":{"und":[{"value":"web","format":null,"safe_value":"web"}]},"field_surname":{"und":[{"value":"services","format":null,"safe_value":"services"}]},"bounce_mail_blocked":false,"force_password_change":"0"}}
Now I want to receive all these objects/strings in separate variables. Like i want to store the "sessid" in a variable String session_id. And so on. I can get the first two (i.e. sessid and session_name) in a simple way with the help of the following code.
response = client.execute(httppost);
BasicResponseHandler handler = new BasicResponseHandler();
String data = handler.handleResponse(response);
jObj = new JSONObject(data);
sessid = jObj.getString("sessid");
Log.d("sessid obj", sessid);
session_name = jObj.getString("session_name");
Log.d("session_name", session_name);
But since I am a noob at Android, I don't know how to get the rest of the data to be saved in variables. The upcoming data cannot be saved in a simple way.
Try with this:
JSONObject j_user = jObj.getJSONObject("user");
String uid = j_user.getString("uid");
...
//And so on with the rest of the fields
{ // json object node
"sessid": "vxkEXkMBUmBByESRlvaxrxSaFTfhDqd8",
"session_name": "SESS88cdfb2f1c420898",
"user": { // json object user
"uid": "60", // string
"name": "abc",
"theme": "",
"signature": "",
"signature_format": "filtered_html",
"created": "13082976",
"access": "1386287",
"login": 1386211,
"status": "1",
"timezone": null,
"language": "",
"picture": null,
"data": { // json object data
"mimemail_textonly": 0 //string
},
....// rest of the json
{ represents json object node
[ represents json array node
To parse
JSONObject jObj = new JSONObject(load());
String sessid = jObj.getString("sessid");
Log.d("sessid obj", sessid);
JSONObject user = jObj.getJSONObject("user");
String uid = user.getString("uid");
Log.d("sessid obj", uid);
To parse data
"data": {
"mimemail_textonly": 0
},
JSONObject data= user.getJSONObject("data");
Log.i(".......",""+data.getString("mimemail_textonly"));
To parser field_centre_reference
"field_centre_reference": { // json object field_centre_reference
"und": [ // json array und
{ // json object node
"nid": "256" //string
}
]
},
JSONObject field= user.getJSONObject("field_centre_reference");
JSONArray jr = field.getJSONArray("und");
JSONObject jb1 = (JSONObject) jr.get(0);
Log.i(".......",""+jb1.getString("nid"));
Check out JacksonParser library, it provides annotations which make your work so easy. And it is one of fastest parsing libraries... You can have it here
Edit:
As an example you can take a look at one of my previous question JacksonParser databind and core cause "Found duplicate file for APK"?
You should notice that the JSON you received is a nested JSON. It is like a Map that one of the value of Map is also a Map.
In your case, there is a JSONObject contains sessid and session_name while is only string, but the "user" is also a JSONObject, so you can parse it level by level.
For more details, you can read http://www.vogella.com/articles/AndroidJSON/article.html
Try this..
Getting
"user": {
"uid": "60",
JSONObject obj_user = jObj.getJSONObject("user");
String uid = obj_user.getString("uid");
"user": {
"uid": "60",
"data": {
"mimemail_textonly": 0
}
JSONObject obj_data = jObj.getJSONObject("data");
String mimemail_textonly = obj_user.getString("mimemail_textonly");
JSONObject obj_roles = jObj.getJSONObject("roles");
String two = obj_roles.getString("2");
"field_centre_reference": {
"und": [
{
"nid": "256"
JSONObject obj_field_centre_reference = jObj.getJSONObject("field_centre_reference");
JSONArray ary_und = obj_field_centre_reference.getJSONArray("und");
JSONObject objve = ary_und.getJSONObject(0);
String nid= objve.getString("nid");
i want to retrive data from one JSONObject in Andother JSONObject
Can any one tell me how to retrive them
My JSONObject is like this
{"udetail":{"ID":238597,"Reference":"AGT-ALIWF_TEST","Provider":"TAL","DropDate":"2012-12-29T13:06:00","abc":"South","def":"2013-01-06T13:06:00","ghi":"North"},"jkl":{"Title":"Mr","FirstName":"LastName_TEST","LastName":"FirstName_TEST LastName_TEST"},"mydetail":{"my":"Model_TESTMake_TEST","hi":"Colour_TEST","tget":"A123 XYZ"}}
String s= "{
"OrderDetails": {
"ID": 238597,
"Reference": "AGT- ALIWF_TEST",
"Provider": "TAL",
"DropDate": "2012-12- 29T13:06:00",
"DropTerminal": "South",
"ReturnDate": "2013-01- 06T13:06:00",
"ReturnTerminal": "North"
},
"CustomerDetails": {
"Title": "Mr",
"FirstName": "LastName_TEST",
"LastName": "FirstName_TEST LastName_TEST"
},
"CarDetails": {
"Make": "Model_TESTMake_TEST",
"Colour": "Colour_TEST",
"Registration": "A123 XYZ"
}
}";
Try this
JSONObject obj=new JSONObject(s);
String orderDetails=obj.getString("OrderDetails");
JSONObject orderjson=new JSONObject(orderDetails);
String Reference=orderjson.getString("Reference");
Same for CarDetails and customer Details
Try this,
To get order details,
JsonObject jobj = new JsonObject(Response);
String str = jobj.getJSONObject("OrderDetails").getString("ID");
customer details,like that
String str1 = jobj.getJSONObject("CustomerDetails").getString("Title");
car details,
String str2 = jobj.getJSONObject("CarDetails").getString("Make");
You should specify in more detail what you want to achieve and what you have tried. If what you've posted is actually a JSONObject and not a String containing some JSON, you should be able to simply fetch e.g. the OrderDetails object using
JSONObject details = <Your JSONObject>.getJSONObject("OrderDetails");
If what you have is just a string with some JSON, create a JSONObject of it first:
JSONObject jo = new JSONObject("{"OrderDetails":{"ID":238 ... }}
JSONObject details = <Your JSONObject>.getJSONObject("OrderDetails");
Also see:
http://developer.android.com/reference/org/json/JSONObject.html#getJSONObject(java.lang.String)