How do I exit a JSON array and enter next object [duplicate] - java
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
How to parse json parsing Using GSON in android
(5 answers)
How to parse JSON in Java
(36 answers)
Closed 10 months ago.
Below is my JSON format, currently my code is in the currencies, and has obtained the currency code successfully, but now i am stuck in terms on how to exit this array and go to languages object.
My current code basically obtains the name of the country, capital and region from the JSON code stuff attached. I also figured out for it to obtain the currency code, but now I want to get the languages part. This is all done within a while loop in java on AndroidStudio.
[
{
"name":"China",
"topLevelDomain":[
".cn"
],
"alpha2Code":"CN",
"alpha3Code":"CHN",
"callingCodes":[
"86"
],
"capital":"Beijing",
"altSpellings":[
"CN",
"Zhōngguó",
"Zhongguo",
"Zhonghua",
"People's Republic of China",
"中华人民共和国",
"Zhōnghuá Rénmín Gònghéguó"
],
"subregion":"Eastern Asia",
"region":"Asia",
"population":1402112000,
"latlng":[
35.0,
105.0
],
"demonym":"Chinese",
"area":9640011.0,
"gini":38.5,
"timezones":[
"UTC+08:00"
],
"borders":[
"AFG",
"BTN",
"MMR",
"HKG",
"IND",
"KAZ",
"PRK",
"KGZ",
"LAO",
"MAC",
"MNG",
"PAK",
"RUS",
"TJK",
"VNM",
"NPL"
],
"nativeName":"中国",
"numericCode":"156",
"flags":{
"svg":"https://flagcdn.com/cn.svg",
"png":"https://flagcdn.com/w320/cn.png"
},
"currencies":[
{
"code":"CNY",
"name":"Chinese yuan",
"symbol":"¥"
}
],
"languages":[
{
"iso639_1":"zh",
"iso639_2":"zho",
"name":"Chinese",
"nativeName":"中文 (Zhōngwén)"
}
],
"translations":{
"br":"China",
"pt":"China",
"nl":"China",
"hr":"Kina",
"fa":"چین",
"de":"China",
"es":"China",
"fr":"Chine",
"ja":"中国",
"it":"Cina",
"hu":"Kína"
},
"flag":"https://flagcdn.com/cn.svg",
"cioc":"CHN",
"independent":true
},
{
"name":"Macao",
"topLevelDomain":[
".mo"
],
"alpha2Code":"MO",
"alpha3Code":"MAC",
"callingCodes":[
"853"
],
"altSpellings":[
"MO",
"澳门",
"Macao Special Administrative Region of the People's Republic of China",
"中華人民共和國澳門特別行政區",
"Região Administrativa Especial de Macau da República Popular da China"
],
"subregion":"Eastern Asia",
"region":"Asia",
"population":649342,
"latlng":[
22.16666666,
113.55
],
"demonym":"Chinese",
"area":30.0,
"timezones":[
"UTC+08:00"
],
"borders":[
"CHN"
],
"nativeName":"澳門",
"numericCode":"446",
"flags":{
"svg":"https://flagcdn.com/mo.svg",
"png":"https://flagcdn.com/w320/mo.png"
},
"currencies":[
{
"code":"MOP",
"name":"Macanese pataca",
"symbol":"P"
}
],
"languages":[
{
"iso639_1":"zh",
"iso639_2":"zho",
"name":"Chinese",
"nativeName":"中文 (Zhōngwén)"
},
{
"iso639_1":"pt",
"iso639_2":"por",
"name":"Portuguese",
"nativeName":"Português"
}
],
"translations":{
"br":"Macau",
"pt":"Macau",
"nl":"Macao",
"hr":"Makao",
"fa":"مکائو",
"de":"Macao",
"es":"Macao",
"fr":"Macao",
"ja":"マカオ",
"it":"Macao",
"hu":"Makaó"
},
"flag":"https://flagcdn.com/mo.svg",
"independent":false
},
{
"name":"Taiwan",
"topLevelDomain":[
".tw"
],
"alpha2Code":"TW",
"alpha3Code":"TWN",
"callingCodes":[
"886"
],
"capital":"Taipei",
"altSpellings":[
"TW",
"Táiwān",
"Republic of China",
"中華民國",
"Zhōnghuá Mínguó"
],
"subregion":"Eastern Asia",
"region":"Asia",
"population":23503349,
"latlng":[
23.5,
121.0
],
"demonym":"Taiwanese",
"area":36193.0,
"timezones":[
"UTC+08:00"
],
"nativeName":"臺灣",
"numericCode":"158",
"flags":{
"svg":"https://flagcdn.com/tw.svg",
"png":"https://flagcdn.com/w320/tw.png"
},
"currencies":[
{
"code":"TWD",
"name":"New Taiwan dollar",
"symbol":"$"
}
],
"languages":[
{
"iso639_1":"zh",
"iso639_2":"zho",
"name":"Chinese",
"nativeName":"中文 (Zhōngwén)"
}
],
"translations":{
"br":"Taiwan",
"pt":"Taiwan",
"nl":"Taiwan",
"hr":"Tajvan",
"fa":"تایوان",
"de":"Taiwan",
"es":"Taiwán",
"fr":"Taïwan",
"ja":"台湾(中華民国)",
"it":"Taiwan",
"hu":"Tajvan"
},
"flag":"https://flagcdn.com/tw.svg",
"cioc":"TPE",
"independent":true
}
]
Related
How to create an object class that can converted to json like this in java? [duplicate]
This question already has answers here: Is there a way to create the bean class from a json response (6 answers) Closed 3 years ago. This is the JSON request that I need to pass to other API, My problem is I dont know how to create an object that can have other object inside. What is the best approach for this, I'll be using ObjectMapper to convert the object into json like this. { "request": { "head": { "version": "1.0.0", "function": "sample.function", "clientId": "clientId", "clientSecret": "clientSecret", "reqTime": "2001-07-04T12:08:56+05:30", "reqMsgId": "reqMessageID", "reserve": "" }, "body": { "occurTime": "2018-03-04T12:08:56+08:00", "bizScene": "SAMPLE_BIZ", "envInfo": { "tokenId": "jkahsdhsjakdhkjsajdsahdkjsakdhsa===", "clientIp": "127.0.0.1", "appVersion": "v0.1.0", "terminalType": "NOP" }, "extendInfo": { "PSID":"87943297427", "PSID_CreatedDate":"2018-01-04T12:08:56+08:00", "mobtelLinkingDate" : "2018-03-04T12:08:56+08:00", "mobtelUnlinkingDate" : "2018-04-04T12:08:56+08:00", "activeLinkedMobtel" : "123756" }, "accountInfo": { "userMobile": "123756" }, "operationInfoDTO" : { "operationOrigin": "TWEETER", }, "operationType": "SAMPLE", "operationResult": "FALSE", } }, "signature": "signature string" }
I gave a name to the root Object a used this website to generate boilerplate bean object "rootObj":{ "request": { "head": { "version": "1.0.0", "function": "sample.function", "clientId": "clientId", "clientSecret": "clientSecret", "reqTime": "2001-07-04T12:08:56+05:30", "reqMsgId": "reqMessageID", "reserve": "" }, "body": { "occurTime": "2018-03-04T12:08:56+08:00", "bizScene": "SAMPLE_BIZ", "envInfo": { "tokenId": "jkahsdhsjakdhkjsajdsahdkjsakdhsa===", "clientIp": "127.0.0.1", "appVersion": "v0.1.0", "terminalType": "NOP" }, "extendInfo": { "PSID":"87943297427", "PSID_CreatedDate":"2018-01-04T12:08:56+08:00", "mobtelLinkingDate" : "2018-03-04T12:08:56+08:00", "mobtelUnlinkingDate" : "2018-04-04T12:08:56+08:00", "activeLinkedMobtel" : "123756" }, "accountInfo": { "userMobile": "123756" }, "operationInfoDTO" : { "operationOrigin": "TWEETER", }, "operationType": "SAMPLE", "operationResult": "FALSE", } }, "signature": "signature string" }
There are some minor syntax errors in your JSON example in line 33 and 36. JSON doesn't like comma after the last element of a list or dictionary. If you remove those and use this JSON as input for http://www.jsonschema2pojo.org/ you'll get corresponding Java classes.
Json query String for getting value with Condition
I want to get the value of vehicleCodeelement where vehicleLease is AS PER LAW OF ENFORCMENT. Could someone please help me with JSON query ? Please find JSON data below. { "StateOffers": [ [{ "vehicleCode": 242214214, "vehiclePart": [{ "#type": "vehiclePart", "segments": [{ "#type": "Segment" "segmentOfferInformation": { "vehicleMiles": 771, "awardFare": false }, "vehicleLease": "AS PER LAW OF ENFORCMENT" } ], "stops": 0 } ] }, { "vehicleCode": 242214214, "vehiclePart": [{ "#type": "vehiclePart", "segments": [{ "#type": "Segment" "segmentOfferInformation": { "vehicleMiles": 771, "awardFare": false }, "vehicleLease": "MY RULE MY WORLD" } ], "stops": 0 } ] } ] ] } This is the expression I have tried: $..vehicleCode[?($..vehicleLease=="AS PER LAW OF ENFORCMENT")
Having trouble accessing fields of JSON using groovy
I'm trying to extract the information from an API response using groovy I want to get to the info stored under the "res" key. Something along the lines of body.measures.02:00:00:02:06:70.res Can not figure out have to access this information without throwing a nullpointerexception. "body":[ { "_id":"70:ee:50:01:fe:96", "place":{ "location":[ -70.863189, 42.273936 ], "altitude":26.154942, "timezone":"America\/New_York" }, "mark":12, "measures":{ "02:00:00:02:06:70":{ "res":{ "1506611038":[ 22, 66 ] }, "type":[ "temperature", "humidity" ] }, "06:00:00:01:97:28":{ "wind_strength":15, "wind_angle":343, "gust_strength":29, "gust_angle":301, "wind_timeutc":1506611083 }, "70:ee:50:01:fe:96":{ "res":{ "1506611086":[ 1007.4 ] }, "type":[ "pressure" ] } }, "modules":[ "02:00:00:02:06:70", "06:00:00:01:97:28" ], "module_types":{ "02:00:00:02:06:70":"NAModule1", "06:00:00:01:97:28":"NAModule2" } } ], "status":"ok", "time_exec":0.017483949661255, "time_server":1506611446 }
body is an array with one element in your case, so you have to do body[0].measures.'02:00:00:02:06:70'.res, e. g. like new groovy.json.JsonSlurper().parseText('''{"body":[ { "_id":"70:ee:50:01:fe:96", "place":{ "location":[ -70.863189, 42.273936 ], "altitude":26.154942, "timezone":"America/New_York" }, "mark":12, "measures":{ "02:00:00:02:06:70":{ "res":{ "1506611038":[ 22, 66 ] }, "type":[ "temperature", "humidity" ] }, "06:00:00:01:97:28":{ "wind_strength":15, "wind_angle":343, "gust_strength":29, "gust_angle":301, "wind_timeutc":1506611083 }, "70:ee:50:01:fe:96":{ "res":{ "1506611086":[ 1007.4 ] }, "type":[ "pressure" ] } }, "modules":[ "02:00:00:02:06:70", "06:00:00:01:97:28" ], "module_types":{ "02:00:00:02:06:70":"NAModule1", "06:00:00:01:97:28":"NAModule2" } } ], "status":"ok", "time_exec":0.017483949661255, "time_server":1506611446 }}''').body[0].measures.'02:00:00:02:06:70'.res
Parsing Json data giving ClassCastException
I am currently using the following JSON parser but keep getting the error Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject. How can I fix this, it has worked many times before. ublic List<String> handleResponse(HttpResponse response) throws ClientProtocolException, IOException { List<String> result = new ArrayList<String>(); String JSONResponse = new BasicResponseHandler() .handleResponse(response); try { // Get top-level JSON Object - a Map JSONObject responseObject = (JSONObject) new JSONTokener( JSONResponse).nextValue(); //Problem Line JSONObject item1 = responseObject.getJSONObject("searchResult"); // Extract value of "Item" key -- a List JSONArray items = item1 .getJSONArray("Item"); Below is what I'm looking to parse { "findItemsAdvancedResponse":[ { "ack":[ "Success" ], "version":[ "1.13.0" ], "timestamp":[ "2015-02-24T18:43:51.778Z" ], "searchResult":[ { "#count":"100", "item":[ { "itemId":[ "381098176861" ], "title":[ " Tokyo Laundry Women's Kenzie Sweatpants - Eclipse Blue - TP1" ], "globalId":[ "EBAY-GB" ], "subtitle":[ "FREE UK DELIVERY | DISPATCHED WITHIN 1 WORKING DAY" ], "primaryCategory":[ { "categoryId":[ "137085" ], "categoryName":[ "Activewear" ] } ], "secondaryCategory":[ { "categoryId":[ "155226" ], "categoryName":[ "Hoodies & Sweats" ] } ], "galleryURL":[ "http:\/\/thumbs2.ebaystatic.com\/pict\/3810981768614040_1.jpg" ], "viewItemURL":[ "http:\/\/www.ebay.co.uk\/itm\/Tokyo-Laundry-Womens-Kenzie-Sweatpants-Eclipse-Blue-TP1-\/381098176861?pt=LH_DefaultDomain_3&var=" ], "paymentMethod":[ "PayPal" ], "autoPay":[ "true" ], "location":[ "United Kingdom" ], "country":[ "GB" ], "shippingInfo":[ { "shippingServiceCost":[ { "#currencyId":"GBP", "__value__":"0.0" } ], "shippingType":[ "Free" ], "shipToLocations":[ "AU", "Europe" ] } ], "sellingStatus":[ { "currentPrice":[ { "#currencyId":"GBP", "__value__":"14.99" } ], "convertedCurrentPrice":[ { "#currencyId":"GBP", "__value__":"14.99" } ], "sellingState":[ "Active" ], "timeLeft":[ "P25DT14H10M23S" ] } ], "listingInfo":[ { "bestOfferEnabled":[ "false" ], "buyItNowAvailable":[ "false" ], "startTime":[ "2014-12-22T08:49:14.000Z" ], "endTime":[ "2015-03-22T08:54:14.000Z" ], "listingType":[ "FixedPrice" ], "gift":[ "false" ] } ], "galleryPlusPictureURL":[ "http:\/\/galleryplus.ebayimg.com\/ws\/web\/381098176861_1_1_1.jpg" ], "condition":[ { "conditionId":[ "1000" ], "conditionDisplayName":[ "New with tags" ] } ], "isMultiVariationListing":[ "true" ], "topRatedListing":[ "false" ] }, { "itemId":[ "131321072184" ], "title":[ "Brave Soul Women's Dallas Parka - Mulberry - DD6 - Size 8-16" ], "globalId":[ "EBAY-GB" ], "subtitle":[ "FREE UK DELIVERY | DISPATCHED WITHIN 1 WORKING DAY" ], "primaryCategory":[ { "categoryId":[ "137085" ], "categoryName":[ "Activewear" ] } ], "secondaryCategory":[ { "categoryId":[ "63862" ], "categoryName":[ "Coats & Jackets" ] } ], "galleryURL":[ "http:\/\/thumbs1.ebaystatic.com\/pict\/1313210721844040_3.jpg" ], "viewItemURL":[ "http:\/\/www.ebay.co.uk\/itm\/Brave-Soul-Womens-Dallas-Parka-Mulberry-DD6-Size-8-16-\/131321072184?pt=LH_DefaultDomain_3&var=" ], "paymentMethod":[ "PayPal" ], "autoPay":[ "true" ], "location":[ "United Kingdom" ], "country":[ "GB" ], "shippingInfo":[ { "shippingServiceCost":[ { "#currencyId":"GBP", "__value__":"0.0" } ], "shippingType":[ "Free" ], "shipToLocations":[ "AU", "Europe" ] } ], "sellingStatus":[ { "currentPrice":[ { "#currencyId":"GBP", "__value__":"19.99" } ], "convertedCurrentPrice":[ { "#currencyId":"GBP", "__value__":"19.99" } ], "sellingState":[ "Active" ], "timeLeft":[ "P15DT14H57M21S" ] } ], "listingInfo":[ { "bestOfferEnabled":[ "false" ], "buyItNowAvailable":[ "false" ], "startTime":[ "2014-10-13T09:36:12.000Z" ], "endTime":[ "2015-03-12T09:41:12.000Z" ], "listingType":[ "FixedPrice" ], "gift":[ "false" ] } ], "galleryPlusPictureURL":[ "http:\/\/galleryplus.ebayimg.com\/ws\/web\/131321072184_1_5_1.jpg" ], "condition":[ { "conditionId":[ "1000" ], "conditionDisplayName":[ "New with tags" ] } ], "isMultiVariationListing":[ "true" ], "topRatedListing":[ "false" ] },
Why do you need a JSONTokener? This is much easier: JSONObject responseObject = new JSONObject(JSONResponse); JSONArray main = responseObject.getJSONArray("findItemsAdvancedResponse"); JSONObject result = main.getJSONObject(0).getJSONArray("searchResult").getJSONObject(0); JSONArray items = result.getJSONArray("item");
Your nextValue() method must be returning a String, which you are then trying to cast to a JSONObject. I would start by splitting the statement up into smaller statements to help isolate the issue. You are instantiating a new object, calling a method on it, and type casting all on the same line. That makes code harder to debug. JSONTokener tokener = new JSONTokener(JSONResponse); Object obj = tokener.nextValue(); if(obj.getClass().equals(JSONObject.class)) { JSONObject responseObject = (JSONObject)obj; } else { System.out.println("Not a JSONObject"); }
Serialization of Chart configuration in Vaadin
I use Vaadin 7. I want to save a Chart configuration and restore it later. I found an interesting thing in com.vaadin.addon.charts.model.Configuration is that you can serialize the configuration into JSON object. Code : chart.getConfiguration().toString(); Result: { "type": "column" }, "title": { "text": "Chart" }, "xAxis": { "categories": [ "f", "e" ], "axisIndex": 0 }, "yAxis": { "min": 0, "title": { "text": "Quantity" }, "axisIndex": 0 }, "tooltip": { "_fn_formatter": "this.series.name +\u0027: \u0027+ this.y +\u0027 (\u0027+ Math.round(this.percentage) +\u0027%)\u0027" }, "plotOptions": { "column": { "stacking": "normal" } }, "series": [ { "data": [ 1, 2 ], "name": "d", "visible": true } ], "exporting": { "enabled": false } } What I want now is build Configuration from that JSON object. Is there a way to that ?
Found it, pretty simple actually : Chart chart = new Chart(); //json is the string containing your JSON object chart.setJsonConfig(json); //you'll have to draw the chart to update it if needed //chart.drawChart();