I am developing an android app, in that i have to make a call to my remote server,it will give me data in terms of json object. in following format.
{
-source: {
LS: " ABCDEF",
name: "XYXA",
point: "77.583859,12.928751"
},
-stores: [
-{
ph: null,
distance: "0.3",
LS: " abcd",
id: 1209,
name: "xyz",
point: "77.583835,12.926359"
},
-{
ph: null,
distance: "0.3",
LS: " abcd",
id: 1209,
name: "xyz",
point: "77.583835,12.926359"
}
]
}
i have confirmed that server is giving me response. But i'm not getting how to access this data in my application.
Can anybody give me a code to access these data.?
Thanking you
JSONObject jsonObject=new JSONObject(responseString);
String LS=jsonObject.getJSONObject("source").get("LS").toString();
String name=jsonObject.getJSONObject("source").get("name").toString();
String point=jsonObject.getJSONObject("source").get("point").toString();
String[] latlng = point.split(",");
String lat=latlng[0];
String lng=latlng[1];
System.out.println("Lat "+lat+" Lng "+lng);
JSONArray jsonArray=jsonObject.getJSONArray("stores");
if (jsonArray.length()>0)
{
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String ph=jsonObject1.get("ph").toString();
String distance=jsonObject1.get("distance").toString();
String LS=jsonObject1.get("LS").toString();
String id=jsonObject1.get("id").toString();
String name=jsonObject1.get("name").toString();
String point=jsonObject1.get("point").toString();
String[] latlng = point.split(",");
String lat=latlng[0];
String lng=latlng[1];
System.out.println("Lat "+lat+" Lng "+lng);
}
}
Here is the complete parsing code section.
Try to parse your JSON response as below:
JSONArray arra = new JSONArray("stores");
for(int i=0;i<arra.length();i++)
{
JSONObject json = arra.getJSONObject(i);
//Retrieve the data from the JSON object
String name= json.getString("name");
String points = json.getString("point");
String loc=json.getString("LS");
}
EDITED:
Extract the lat,long from string point you need to use the StringTokenizer to split the string as below:
StringTokenizer stoken = new StringTokenizer(points, ",");
while (stoken.hasMoreTokens()) {
System.err.println(stoken.nextToken());
}
Related
I´m trying to filter all values in name where id = 1 and save to an array.
This is the output I get from my WS:
[{id=1; name=Des Moines; }, {id=2; name=Cedar Rapids; }, {id=3; name=Yakima; },{id=4; name=Fort Dodge; }, {id=1; name=Iowa City; }]
if I try get property it splits my content.
Could anyone help me out on how to get the desire output?
That's JSON data, you should consider parse the data into an object , there are a lot of JSON java parsers , you could read something about GSON:
https://github.com/google/gson/blob/master/UserGuide.md
You can try something like the following
your json string must be like:
["items":{id=1; name=Des Moines; }, {id=2; name=Cedar Rapids; }, {id=3; name=Yakima; },{id=4; name=Fort Dodge; }, {id=1; name=Iowa City; }]
JSONObject jsonObject = null;
jsonObject = new JSONObject("your json string goes here!!");
String items = jsonObject.getString("items");
JSONArray array = new JSONArray(weather);
ArrayList<JSONObject > arrList = new ArrayList<JSONObject >();
for(int i = 0; i < array.length(); i++)
{
JSONObject jsonObject1 = array.getJSONObject(i);
arrList.add(jsonObject1 );
String id = jsonObject1.get("id").toString();
String name = jsonObject1.get("name").toString();
}
I've got problem with parsing JSON. I've got response from webservice like this :
{
"data": {
"1": [
{
"id": "2",
"name": "Szelki bezpieczeństwa",
"quantity": "1",
"note": null,
"picture_id": null,
"code": "CCCCCCCCCCCCCC"
},
{
"id": "3",
"name": "Kalosze do brodzenia, wysokie lub biodrowe",
"quantity": "2",
"note": "Do wymiany",
"picture_id": null,
"code": "DDDDDDDDDDDDDD"
}
],
"2": [
{
"id": "1",
"name": "Spodnie dla pilarza z ochroną przed przecięciem, klasa min. 1 (wg PN-EN 381-5)",
"quantity": "2",
"note": "Uszkodzone",
"picture_id": null,
"code": "DAAD086F690E1C36"
}
]
}
}
I try to parse it into PART object and add it to List but somewhere I'm making mistake because object is not being parsed.
public void onResponse(String response) {
Log.e(TAG, "onResponse WHOLE: " + response);
try {
JSONObject responseJSONObject = new JSONObject(response);
String arrayString = responseJSONObject.getJSONArray("data").toString();
JSONArray responseJSONArray = new JSONArray(arrayString);
Part tempCarEquipment;
int index = 1;
for (int i = 0; i < responseJSONArray.length(); i++,index++) {
JSONObject object = responseJSONArray.getJSONObject(index);
JSONArray response2 = object.getJSONArray(Integer.toString(index));
String id = object.getJSONObject(Integer.toString(i)).getString("id");
String name= object.getJSONObject(Integer.toString(i)).getString("name");
String quantity= object.getJSONObject(Integer.toString(i)).getString("quantity");
String picture_id= object.getJSONObject(Integer.toString(i)).getString("picture_id");
String code= object.getJSONObject(Integer.toString(i)).getString("code");
tempCarEquipment = new Part(name,quantity,"",picture_id,code,id,"",0);
wholeList.add(tempCarEquipment);
Log.e(TAG, "wholeList: " + wholeList.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in advance fo every help! :)
JSON Parsing
You have to use the iterator for this kind of response
basic example of iterator is in this link.
You are trying to parse map as an array here:
String arrayString = responseJSONObject.getJSONArray("data").toString();
Try something like this instead:
List<JSONArray> objects = new ArrayList<>();
Iterator<String> keys = responseJSONObject.getJSONObject("data").keys();
while(keys.hasNext()) {
objects.add(responseJSONObject.getJSONObject("data").get(keys.next());
}
// rest of your stuff
Alternatively, consider using GSON to parse JSON responses using POJOs.
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
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.
How to parse code, messge, calctime,city,id,country, name from following
use this URL : http://openweathermap.org/data/2.1/forecast/city/524901
{ "cod":"200","message":"kf","calctime":0.0342,"url":"http:\/\/openweathermap.org\/city\/524901",
"city":
{
"id":524901,
"coord":
{
"lon":37.615555,"lat":55.75222
},
"country":"RU","name":"Moscow","dt_calc":1356948005,"stations_count":6
},
Follow the below code:
JSONObject jObj=new JSONObject(jsonResponse);
String msg=jObj.getString("message");
String calctime=jObj.getString("calctime");
Use below code for parse code, messge, calctime,city,id,country, name from above url, it will solve your problem.
JSONObject mJsonObj = new JSONObject(mJsonResponse);
String mCode = mJsonObj.getString("cod");
String mMessage = mJsonObj.getString("message");
String mCalcTime = mJsonObj.getString("calctime");
JSONObject mJsonCityObj = mJsonObj.getJSONObject("city");
String mId = mJsonCityObj.getString("id");
String mConuntry = mJsonCityObj.getString("country");
String mName = mJsonCityObj.getString("name");