I am new to JSON. I know the forecast is an array, but how do I access elements date and text? I know where the problem is: It seems i cannot get access to forecast array, as this gives a null.
JSONArray jArr = data.getJSONArray("forecast");
what is the proper notation to get access to the forecast array. I was trying
`JSONArray jArr = data.getJSONObject("item").getJSONObject("condition").getJSONArray("forecast");
but this notation still did not give me access to the array. What notation will give me correct reference to forecast array?
"item": {
"title": "Conditions for Kingston, Saint Andrew, JM at 09:00 PM EST",
"lat": "18.015711",
"long": "-76.79731",
"link": "http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-109251/",
"pubDate": "Sat, 22 Oct 2016 09:00 PM EST",
"condition": {
"code": "27",
"date": "Sat, 22 Oct 2016 09:00 PM EST",
"temp": "77",
"text": "Mostly Cloudy"
},
"forecast": [
{
"code": "32",
"date": "20 Oct 2016",
"day": "Thu",
"high": "35",
"low": "26",
"text": "Sunny"
},
{
"code": "34",
"date": "21 Oct 2016",
"day": "Fri",
"high": "34",
"low": "28",
"text": "Mostly Sunny"
},
{
"code": "26",
"date": "22 Oct 2016",
"day": "Sat",
"high": "37",
"low": "32",
"text": "Cloudy"
},
{
"code": "23",
"date": "23 Oct 2016",
"day": "Sun",
"high": "37",
"low": "34",
"text": "Breezy"
},
I was trying something like this, but my android app was crashing? I just need help in accessing the elements in the array to set them on some textfields.
public void populate(JSONObject data) throws JSONException {
JSONArray jArr = data.getJSONArray("forecast");
for(int i=0;i<jArr.length();i++){
JSONObject jDayForecast = jArr.getJSONObject(i);
String date = jDayForecast.getString("date");
String text = jDayForecast.getString("text");
}
}
here is the error in stacktrace.
54.516 27220-27220/net.digitalphantom.app.weatherapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.digitalphantom.app.weatherapp, PID: 27220
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String net.JamCast.app.weatherapp.data.Forecast.getDate()' on a null object reference
at net.JamCast.app.weatherapp.WeatherActivity$override.serviceSuccess(WeatherActivity.java:363)
at net.JamCast.app.weatherapp.WeatherActivity$override.access$dispatch(WeatherActivity.java)
at net.JamCast.app.weatherapp.WeatherActivity.serviceSuccess(WeatherActivity.java:0)
at net.JamCast.app.weatherapp.service.YahooWeatherService$1.onPostExecute(YahooWeatherService.java:95)
at net.JamCast.app.weatherapp.service.YahooWeatherService$1.onPostExecute(YahooWeatherService.java:37)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
define a java bean class, use GSON jar translate json string to class object, then you can get text element by your object. please search in google sample.
Related
I have two objects of type ClassA<List<List<String>>> which retruns as a JSON from controller. I want to merge these two objects based on two properties(country and operator) if they are equal. Example JSON looks like
#RequestMapping(value = "/controller3"method= RequestMethod.GET produces= MediaType.APPLIACTION_JSON_VALUE)
public ClassA<List<List<String>>> process(HttpServletRequest request) {
ClassA<List<List<String>>> one = service.getvalues();
ClassA<List<List<String>>> two = service.getvaluestwo();
return merge(one, two);
}
JSON1 looks like
"title": "Source",
"dateRange": "23 August 2017 - 21 November 2017",
"total": 336,
"pageSize": 336,
"pageNum": -1,
"nextPageKey": "",
"results": [
[
"India",
"Idea",
"30"
],
"headers": [
"Country",
"Operator",
"Count"
]
JSON2 looks like
"title": "Source",
"dateRange": "23 August 2017 - 21 November 2017",
"total": 336,
"pageSize": 336,
"pageNum": -1,
"nextPageKey": "",
"results": [
[
"India",
"Idea",
"20"
],
"headers": [
"Country",
"Operator",
"Count"
]
I want the Resultant JSON would extracted from RestController from the type ClassA<List<List<String>>> would looks like
"title": "Source",
"dateRange": "23 August 2017 - 21 November 2017",
"total": 336,
"pageSize": 336,
"pageNum": -1,
"nextPageKey": "",
"results": [
[
"India",
"Idea",
"30",
"20",
"50"
],
"headers": [
"Country",
"Operator",
"Count1",
"Count2",
"Total"
]
if there is no match then aggregate them as with zero count of each other.
Can you guys help me?
Hi all I am getting a following json from Wordpress rest APi Call
[
{
"ID": 248,
"post_title": "test post",
"post_author": "admin",
"excerpt": "",
"url": "http://localhost/wp-learning/?p=248",
"permalink": "http://192.168.10.31/wp-learning/test-post/",
"post_date": "2017-08-07 09:15:57",
"comment_count": "2",
"category": [
{
"term_id": 1,
"name": "Uncategorized",
"slug": "uncategorized",
"term_group": 0,
"term_taxonomy_id": 1,
"taxonomy": "category",
"description": "",
"parent": 0,
"count": 1,
"filter": "raw",
"cat_ID": 1,
"category_count": 1,
"category_description": "",
"cat_name": "Uncategorized",
"category_nicename": "uncategorized",
"category_parent": 0
}
],
"views": "4",
"featured_image": false
},
{
"ID": 247,
"post_title": "The Coolest Vanity Apps for You and Your Girls",
"post_author": "admin",
"excerpt": "",
"url": "http://td_uid_79_598817d2cebf2",
"permalink": "http://192.168.10.31/wp-learning/the-coolest-vanity-apps-for-you-and-your-girls/",
"post_date": "2017-08-07 07:33:38",
"comment_count": "0",
"category": [
{
"term_id": 15,
"name": "Beauty",
"slug": "beauty",
"term_group": 0,
"term_taxonomy_id": 15,
"taxonomy": "category",
"description": "On each category you can set a Category template style, a Top post style (grids) and a module type for article listing.",
"parent": 14,
"count": 17,
"filter": "raw",
"cat_ID": 15,
"category_count": 17,
"category_description": "On each category you can set a Category template style, a Top post style (grids) and a module type for article listing.",
"cat_name": "Beauty",
"category_nicename": "beauty",
"category_parent": 14
}
],
"views": "0",
"featured_image": "http://192.168.10.31/wp-learning/wp-content/uploads/2017/08/3.jpg"
}
]
I am problem in fetching the tag name "featured_image". what type of datatype is it? i tried
jsonObj.getString("featured_image");
for this it gave me error JSONObject["featured_image"] is not a String.
also
resultsObj.getJSONObject("featured_image").toString()
for this it gave me error JSONObject["featured_image"] is not a JSONObject.
You are doing resultsObj.getJSONObject("featured_image").toString() which asks to get a JSON Object out of the Key/Value at 'featured_image'.
But we can see that the value is a string, or a bool:
"featured_image": "http://192.168.10.31/wp-learning/wp-content/uploads/2017/08/3.jpg"
"featured_image": false
So you should not call getJSONObject() on this key, at all.
Based on your JSON Structure, it looks like the "featured_image" is of boolean type, it is not string or object.
I think its inner json problem
try like this :
JSONObject category = jsonObj.getJSONObject("category");
category.getJSONObject("featured_image");
You can use following code, I didn't tested but that can be helpful in determining the data type and based on the type you can decide which method needs to be called.
So use:
JsonValue type = resultsObj.get("featured_image").getValueType();
if (type.getValueType() == JsonValue.ValueType.TRUE || type.getValueType() == JsonValue.ValueType.FALSE){
// call boolean method
boolean bValue = resultsObj.get("featured_image").getAsBoolean()
}else{
//based on you type you can call respective method.
}
Refer following link:
JsonValueType
getValueType
Here is the JSON response of a video for youtube data analytics:
{
"kind": "youtube#videoListResponse",
"etag": "\"q5k97EMVGxODeKcDgp8gnMu79wM/nKD2hgTXHwAf_Y8YHghPkBlZJcs\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"q5k97EMVGxODeKcDgp8gnMu79wM/GLcJdYlEeecN5amO819w0A1mSqU\"",
"id": "PK_HFb8tkUs",
"snippet": {
"publishedAt": "2016-03-14T01:52:34.000Z",
"channelId": "UCHqC-yWZ1kri4YzwRSt6RGQ",
"title": "Full Speech: Donald Trump HUGE Rally in Boca Raton, FL (3-13-16)",
"description": "Sunday, March 13, 2016: GOP Presidential candidate Donald Trump held a campaign rally in Boca Raton, FL at Sunset Cove Amphitheater and spoke to a massive crowd of tens of thousands of supporters.\n\nFull Speech: Donald Trump Rally in Boca Raton, FL (3-13-16)",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/PK_HFb8tkUs/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/PK_HFb8tkUs/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/PK_HFb8tkUs/hqdefault.jpg",
"width": 480,
"height": 360
},
"standard": {
"url": "https://i.ytimg.com/vi/PK_HFb8tkUs/sddefault.jpg",
"width": 640,
"height": 480
}
},
"channelTitle": "Right Side Broadcasting",
"tags": [
"Donald Trump",
"Live Stream",
"Boca Raton",
"Florida",
"Rally",
"Speech",
"Politics",
"Republican Party"
],
"categoryId": "25",
"liveBroadcastContent": "none",
"localized": {
"title": "Full Speech: Donald Trump HUGE Rally in Boca Raton, FL (3-13-16)",
"description": "Sunday, March 13, 2016: GOP Presidential candidate Donald Trump held a campaign rally in Boca Raton, FL at Sunset Cove Amphitheater and spoke to a massive crowd of tens of thousands of supporters.\n\nFull Speech: Donald Trump Rally in Boca Raton, FL (3-13-16)"
},
"defaultAudioLanguage": "en"
},
"contentDetails": {
"duration": "PT2H41M2S",
"dimension": "2d",
"definition": "hd",
"caption": "false",
"licensedContent": true
},
"status": {
"uploadStatus": "processed",
"privacyStatus": "public",
"license": "youtube",
"embeddable": true,
"publicStatsViewable": true
},
"statistics": {
"viewCount": "371675",
"likeCount": "7592",
"dislikeCount": "586",
"favoriteCount": "0",
"commentCount": "1397"
}
}
]
I would only like to extract the viewCount for example from the above response. How do I do that in Java? I have obtained the above response in a string but how do I extract just those single values like viewCount? An example is well appreciated.
You would have to traverse the JSON array to get the viewCount field. I can't give you the exact code to use as you have not told us what JSON library you are using, but here's some pseudocode.
// If json is the object containing the JSON data
viewCount = json["items"][0]["statistics"]["viewCount"];
From the "items" array, you get the first element, then the "statistics" object from that element, then the "viewCount" field from the statistics object.
Try this -
String jsonString="";
JsonParser jParser= Json.createParser(new ByteArrayInputStream(jsonString.getBytes()));
while(jParser.hasNext()){
if(jParser.next()==Event.KEY_NAME){
if(jParser.getString().equals("viewCount")){
jParser.next();
System.out.println(jParser.getString());
}
}
}
The library should be imported correctly. Please refer -
https://jsonp.java.net/download.html.
I have this json string:
I want to extract all the ids that are after the node of number:"0","1","2"...etc.
I have succeeded to get a single id by using jsonpath: $.response.data.0.id and got "15124".
but i'm looking for a jsonpath that will extract all the ids in the Json String.
in other words this is the expexted output: 15124,13498,14296,13364,14060,13672.
This is the Json String i have:
{
"response": {
"code": 200,
"msg": "Success",
"data": {
"0": {
"id": "15124",
"name": " yoav (yoavshaki#yahoo.com) - 301519506662355",
"network_id": 1,
"network_type": "Facebook",
"currency": "USD",
"currency_info": {
"prefix": "$",
"postfix": "",
"name": "US Dollars"
},
"timezone": {
"id": 139,
"code": "IST",
"region": "Asia",
"locality": "Jerusalem",
"offset": 3,
"facebook_code": 70
}
},
"1": {
"id": "13498",
"name": "(Not in used) Daniel - 30138444",
"network_id": 1,
"network_type": "Facebook",
"currency": "USD",
"currency_info": {
"prefix": "$",
"postfix": "",
"name": "US Dollars"
},
"timezone": {
"id": 92,
"code": "PST",
"region": "America",
"locality": "Los_Angeles",
"offset": -7,
"facebook_code": 1
}
},
"2": {
"id": "14296",
"name": "Daniel - ComeOn (bingocafe#walla.com - 1375713835981039)",
"network_id": 1,
"network_type": "Facebook",
"currency": "USD",
"currency_info": {
"prefix": "$",
"postfix": "",
"name": "US Dollars"
},
"timezone": {
"id": 92,
"code": "PST",
"region": "America",
"locality": "Los_Angeles",
"offset": -7,
"facebook_code": 1
}
},
"3": {
"id": "13364",
"name": "Erez - 116060088528093",
"network_id": 1,
"network_type": "Facebook",
"currency": "USD",
"currency_info": {
"prefix": "$",
"postfix": "",
"name": "US Dollars"
},
"timezone": {
"id": 92,
"code": "PST",
"region": "America",
"locality": "Los_Angeles",
"offset": -7,
"facebook_code": 1
}
},
"4": {
"id": "14060",
"name": "Erez - NordicBet (gianniciano82#gmail.com - 105134566315107)",
"network_id": 1,
"network_type": "Facebook",
"currency": "USD",
"currency_info": {
"prefix": "$",
"postfix": "",
"name": "US Dollars"
},
"timezone": {
"id": 139,
"code": "IST",
"region": "Asia",
"locality": "Jerusalem",
"offset": 3,
"facebook_code": 70
}
},
"5": {
"id": "13672",
"name": "Erez - alon.dan - 1378526859026272",
"network_id": 1,
"network_type": "Facebook",
"currency": "USD",
"currency_info": {
"prefix": "$",
"postfix": "",
"name": "US Dollars"
},
"timezone": {
"id": 92,
"code": "PST",
"region": "America",
"locality": "Los_Angeles",
"offset": -7,
"facebook_code": 1
}
}
}
}
}
Thanks for all the helpers!
GSON library is a good option to convert java object to json string and vise versa.
for converting json to java object use: fromJson(String, Class)
for converting java object to json string use: toJson(Object)
Here is the sample code using [Gson#fromJson()] to convert JSON string into java Map.
Find more examples...
Sample code:
BufferedReader reader = new BufferedReader(new FileReader(new File("resources/json.txt")));
Gson gson = new Gson();
Type type = new TypeToken<Map<String, Map<String, Object>>>() {}.getType();
Map<String, Map<String, Object>> map = gson.fromJson(reader, type);
Map<String, Map<String, Object>> innerMap = (Map<String, Map<String, Object>>) map.get("response").get("data");
for (String key : innerMap.keySet()) {
System.out.println("key:" + key + " id:" + innerMap.get(key).get("id"));
}
output:
key:0 id:15124
key:1 id:13498
key:2 id:14296
key:3 id:13364
key:4 id:14060
key:5 id:13672
Thanks Syam S. for your answer.
$.response.data.*.id indeed work!
I am using GSON library.
I have a programm which returns JSON.
JSON constructs and returns in this way:
Gson gson = new Gson();
//findNewComments returns List<Comment> comments
return gson.toJson(service.findNewComments(id,lastId));
So the result is:
[
{
"id": 43,
"entryId": 19,
"author": " m8w46",
"body": "mw86",
"date": "WED 9, 2011"
},
{
"id": 44,
"entryId": 19,
"author": " n7w4",
"body": "nw77w4",
"date": "WED 9, 2011"
}
]
But this array must be named as "comments"!
"comments": [
{
"id": 43,
"entryId": 19,
"author": " m8w46",
"body": "mw86",
"date": "WED 9, 2011"
},
{
"id": 44,
"entryId": 19,
"author": " n7w4",
"body": "nw77w4",
"date": "WED 9, 2011"
}
]
How can i do that?
Not sure if this is acceptable to you but:
public class CommentWrapper {
List<Comments> comments;
public CommentWrapper(List<Comment> comments) {
this.comments = comments;
}
}
Then you can do:
return new Gson().toJson(new CommentWrapper(service.findNewComments(id,lastId)));
Which results in:
{
"comments": [
....your data here...
]
}
Not sure if the object syntax is acceptable to you or not.
Aside from wrapper object, you can also use a simple java.util.Map with single entry, possibly bit less code.