I'm trying to parse weather information from a http://www.worldweatheronline.com JSON feed. This is the format that it comes in:
{ "data" : { "current_condition" : [ { "cloudcover" : "75",
"humidity" : "100",
"observation_time" : "10:01 PM",
"precipMM" : "0.0",
"pressure" : "1015",
"temp_C" : "3",
"temp_F" : "37",
"visibility" : "4",
"weatherCode" : "143",
"weatherDesc" : [ { "value" : "Mist" } ],
"weatherIconUrl" : [ { "value" : "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0006_mist.png" } ],
"winddir16Point" : "N",
"winddirDegree" : "360",
"windspeedKmph" : "11",
"windspeedMiles" : "7"
} ],
So there is the current_condition JSONArray, which I have managed to obtain values from. But then how do I read the values from the inner arrays weatherDesc or weatherIconUrl?
Here is my code for reading precipMM, pressure, temp_C, etc:
String precipMM = null;
try {
JSONObject data = json.getJSONObject("data");
JSONArray current_condition = data.getJSONArray("current_condition");
for(int i = 0; i < current_condition.length(); i++) {
precipMM = current_condition.getJSONObject(i).getString("precipMM");
}
} catch (JSONException e) {
e.printStackTrace();
}
It's as simple as
current_condition.getJSONArray()
As also with json parsing I would suggest looking at this library
http://jackson.codehaus.org/
EDIT After you comment
The code you posted could be improved a lot. You are iterating through the array for each value. You can do the same thing with the array. Just call .getJsonArray(), instead of .getJsonObject(). However this means your code is throwing an error for each of the other values. I would again recommend the Jackson library
weatherDesc and weatherIconUrl are provided as array, so you can access by item i.e. inside a for loop.
Just use same command as you do it for current_condition
Related
for example:
{
"error": false,
"message": "",
"code": "",
"ver": "v1.0.0",
"base": "https://,,,,,,,,,.com/",
"count": 1,
"updated": "2020-10-28T19:40:51+03:00",
"data": [
{
"id": "44",
"slug": "human-resources",
"name": "Human resources",
"img1": null,
"img2": "page_44/1560347480_2.jpg",
"date": "2019-05-31",
"des": "'vvvvvv.v",
"sendMail": "info#....",
"iframe_url": "ff/ff"
}
]
}
this is api json response.
I want only "data": [] value, not the rest.
Is there a way I can avoid creating data class for whole api response instead just request "data": [..] value?
I am using Android Studio Kotlin Retrofit Moshi
If I understand your question correctly, you just want to extract data from that JSON string. You can do that with:
JSONArray dataArray;
try {
dataArray = new JSONObject(yourString).optJSONArray("data");
} catch (JSONException e) {
// whatever
}
for (int i = 0; i < dataArray.length(); ++i) {
// do whatever you want with each object:
String name = dataArray.optJSONObject(i).optString("name");
}
iam trying to parse the json data which is shown below.i got output for other Json response by following this procedure but for this i cant get data.
{
"totalResults": 7,
"startIndex": 1,
"hasMoreResults": false,
"itemsPerPage": 10,
"results": [
{
"offering_temp_id": {
"displayName": "Cool Course",
"id": "cours000000000004841",
"course_no": "00006081",
"version": null
},
"delivery_id": {
"displayName": "Instructor-Led",
"id": "eqcat000000000000004"
},
"student_id": {
"id": "emplo000000006156648",
"displayName": "Venkat Rao",
"person_no": "VRAO"
},
"reg_no": "00008341",
"wlist_on": "2017-08-17T08:59:39.843-0400",
"wlist_priority": 5,
"Max_Count": null,
"Current_Count": null,
"is_no_show": false,
"is_walk_in": false,
"offering_action_id": {
"id": "ofapr000000000013441",
"displayName": "00009081"
},
"class_id": {
"id": "class000000000006981",
"displayName": "Cool Course"
},
"elements_to_complete": 0,
"status": "100",
"id": "regdw000000000012581"
},
// total 7 fields
],
"facets": []
}
And iam using the parser procedure as follows
public class EnrollmentParser {
public ArrayList<EnrollmentData> getData(String respnose)//EnrollmentData is my pojo class contains 4 strings and its getters and setters
{
ArrayList<EnrollmentData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(respnose);
JSONArray array = mainObj.getJSONArray("results");
for(int i = 0;i<array.length();i++)
{
EnrollmentData data = new EnrollmentData();
JSONObject resObj = array.getJSONObject(i);
data.setReg_num(resObj.getString("reg_no"));
data.setElements_to_complete(resObj.getString("elements_to_complete"));
data.setW_list_on(resObj.getString("wlist_on"));
data.setW_list_priority(resObj.getString("wlist_priority"));
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
}
when iam trying to display the dataList returned from above method i didnt get any data i got response like
Suggest me any changes that are required to get the response
There is no faulty parsing code, everything is fine (although better use optString).
By default , the toString function will return the type '#' reference value so
You need to override toString in EnrollmentData class to see the actual content inside EnrollmentData object
You can also collect your list objects as single string using
String str = Arrays.toString(yourList.toArray());
How to print out all the elements of a List in Java?
Why don't you use Gson to convert json into object easily instead of getting the field and set them one by one?
You may check out
https://github.com/google/gson
in the past i have already parsed a json file from url to local sqlite database and the json source was like the following one:
[
{
"origin": "accommodation",
"parent": "",
"en": "Accommodation"
},
{
"origine": "book",
"parent": "shopping",
"en": "Book"
},
{
"origin": "university",
"parent": "education",
"en": "University"
}
]
But now it seems to be different. I validate the following json file so i'm sure it is a valid json, but it is formatted in a different way, so i do not know how to parse it in the right way. In addition this time i would put the content in an ArrayList. Here is the json file:
{
"city1": {
"item1": {
"score": 6196.58,
"step": 0.00423,
"name": "User 1",
"form": "yellow"
},
"item2": {
"score": 106.86,
"step": 2.5822,
"name": "User 2",
"form": "yellow"
},
"item3": {
"score": 671.48,
"step": 0.387,
"name": "User 3",
"form": "yellow"
},
},
"misc": {
"online_users": {
"kind1": 18,
"kind2": 3
},
"ops": [
""
]
},
"city2": {
"item1": {
"score": 6196.58,
"step": 0.00405,
"name": "User 1",
"form": "yellow"
},
"item2": {
"score": 179563.93,
"step": 0.000138,
"name": "User 2",
"form": "yellow"
},
"min_size": {
"line": 10
},
"out_of_sync": [
"0e888069530497506433b5f0cacb",
"b428fa3a9b9e13cf8b26196bfcc7",
"f42442a2e46523f059809f83f1a9"
],
},
}
Can you tell me how to handle these values and how to put in some arraylist?
There are several ways to do this, but I'll post the way I feel like makes the most sense. If you don't mind putting this in separate arrays you can do this:
String stringOfJSONCode = <read in the JSON here>;
JSONObject json = new JSONObject(stringOfJSONCode);
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (Exception e) {
}
}
You need to use an iterator to loop through a JSONObject. You could use any other loop to loop through JSONArrays. This will iterate through the outer objects, like city1, misc, city2. The key will be either city1, misc, or city2.
If you want to get those, just add this within the 'try'
JSONObject object = json.getJSONObject(key);
or
JSONArray array = json.getJSONArray(key);
depending on what you're trying to get. Once you have these, you can do the following:
JSONObject city1 = object.getJSONObject("item1");
List<String> jsonList = new ArrayList<String>();
jsonList.add(object.getDouble("score"));
jsonList.add(object.getDouble("step"));
jsonList.add(object.getString("name"));
jsonList.add(object.getString("form"));
If you are not sure if it will be item1 or whatever, you can iterate through it again using the iterator and add each item in dynamically. Also you can make another try-catch, try to get a JSONArray, if it is not an array it will go in the catch, and then iterate through the object.
You could also make a hashmap or 2D array to add everything in the same array.
Hope this helps
Why don't you let jackson mapper do it's magic?
The only thing you'll need then would be appropriate DTO classes.
Below is my code which parse JSON if I fetch "id". If I don't give id then the JSON array will not show. How do i show JSON without id?
How do I parse JSONArray without "id" if I don't give id in JSON file then array will not show it is necessary to give "id" in JSON file???
this json array not show
{
"status": 1,
"data": [
{
"title": "Elementary"
},
{
"title": "Middle"
},
{
"title": "High"
},
{
"title": "Atypical"
}
]
}
this json array will show
{
"status": 1,
"data": [
{
"id": "1",
"title": "Elementary"
},
{
"id": "2",
"title": "Middle"
},
{
"id": "3",
"title": "High"
},
{
"id": "4",
"title": "Atypical"
}
]
}
Code:
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
// Category_ID.add(Long.parseLong(object.getString("id")));
Category_name.add(object.getString("title"));
}
You are accessing the id property here:
Category_ID.add(Long.parseLong(object.getString("id")));
When it is not there this will throw an exception.
Try This Code while parsing your json:
if(object.has("id"))
{
Category_ID.add(Long.parseLong(object.getString("id")));
}
else
{
// add default id
}
hope this will work for you.
I suppose you want your code to work for both JSON samples.
You can perform a check if "id" exists or not and then parse accordingly.
You can perform this check using the below code.
String id = object.optString("id");
//JSONObject.optString("id") will return id's value if it exists or else will return empty string.
if(!"".equals(id)){
Category_ID.add(Long.parseLong(id));
//this code will run only when your JSON contains id
}
else
{
//this code will run when your JSON doesn't have id field.
Category_ID.add();
}
I'm getting my position from an address, I use this website:
I get JSON data, but I dont know how to read it in my Android app.
{
"name": "plaza mayor 1 madrid España",
"Status": {
"code": 200,
"request": "geocode"
},
"Placemark": [ {
"id": "p1",
"address": "Plaza Mayor, 1, 28012 Madrid, España",
"AddressDetails": {
"Accuracy" : 8,
"Country" : {
"AdministrativeArea" : {
"AdministrativeAreaName" : "Comunidad de Madrid",
"SubAdministrativeArea" : {
"Locality" : {
"LocalityName" : "Madrid",
"PostalCode" : {
"PostalCodeNumber" : "28012"
},
"Thoroughfare" : {
"ThoroughfareName" : "Plaza Mayor, 1"
}
},
"SubAdministrativeAreaName" : "Madrid"
}
},
"CountryName" : "España",
"CountryNameCode" : "ES"
}
},
"ExtendedData": {
"LatLonBox": {
"north": 40.4164186,
"south": 40.4137207,
"east": -3.7053139,
"west": -3.7080118
}
},
"Point": {
"coordinates": [ -3.7066379, 40.4150359, 0 ]
}
} ]
}
How can I read the "coordinates" tag?
Thank you in advance!
parse it, to begin with, then access the various elements :
JSONObject response = new JSONObject(responseAsString);
JSONObject point = response.getJSONArray("Placemark").getJSONObject(0).getJSONObject("Point");
double lat = point.getJSONArray("coordinates").getDouble(0);
and so on
I would suggest using some sort of framwork to handle your Json data, here's a good aexample. Then you can handle your data as a regular object.
Sending and Parsing JSON Objects
Good luck!