Unable to parse JSON, Showing error message "JSONObject["other"] not found" - java

Below is the code snippet for the utility which I've used to fetch data.
Below are sample JSON in which I have to fetch the value of Other/Vehicle/Properties, but I'm getting an error message.
Please suggest what things I need to add to the utility?
I need to get the value of Other/Vehicle/Properties.
Please suggest what things I need to change in the Utility so that nested property also fetched from JSON.
public class TestUtil {
public static JSONObject responsejson;
public static String getValueByJPath(JSONObject responsejson, String jpath){
Object obj = responsejson;
for(String s : jpath.split("/"))
if(!s.isEmpty())
if(!(s.contains("[") || s.contains("]")))
obj = ((JSONObject) obj).get(s);
else if(s.contains("[") || s.contains("]"))
obj = ((JSONArray) ((JSONObject) obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("\\[")[1].replace("]", "")));
return obj.toString();
}
}
JSON Format:
{
"coverageEndDate": "02/28/2019",
"coverageStartDate": "03/01/2018",
"coverageType": "Personal",
"error": {
"code": 0,
"message": ""
},
"firstName": "Ronnie",
"insuredItems": {
"other": [{
"coverageEndDate": "02/28/2019",
"coverageStartDate": "03/01/2018",
"description": "Hunter Marin Passage 450",
"id": 14
}],
"properties": [{
"address": "31 LAKEWOOD RD, WEST BEND, WI 53090",
"coverageEndDate": "02/28/2019",
"coverageStartDate": "03/01/2018",
"deductible": 5000,
"description": "31 LAKEWOOD RD, WEST BEND, WI 53090",
"id": "113",
"limit": 2000000
}],
"vehicles": [{
"coverageEndDate": "02/28/2019",
"coverageStartDate": "03/01/2018",
"deductible": "$500 Comprehensive\n$500 Collision",
"description": "2016 Ford Explorer",
"id": "126",
"limit": "$100,000",
"make": "FORD",
"model": "EXPLORER",
"transportationExpense": "$30 per day and $900 max",
"vin": "1G1FA1E38F2131121",
"year": 2016
}, {
"coverageEndDate": "02/28/2019",
"coverageStartDate": "06/18/2018",
"deductible": "$500 Comprehensive\n$500 Collision",
"description": "2017 Dodg Durango",
"id": "127",
"limit": "$100,000",
"make": "DODG",
"model": "DURANGO",
"transportationExpense": "$30 per day and $900 max",
"vin": "2G1XER366DE4DE3H5",
"year": 2007
}]
},
"lastName": "James Dio",enter code here
"policyNumber": "5519930"
}

Use normal parser from jackson lib by this example

Related

best approach to parse json response in spring boot

I am consuming a rest-end point using rest template which returns below josn messages.
object Wrappers is better approach or json object parsing is better ?
[
{
"id": "UAMwcI",
"messageId": "PyXPTk-6XUBhbONWZ2DOw3___pFykwV5bQ",
"timestamp": 1574330759814,
"type": "MESSAGESENT",
"initiator": {"user": {
"userId": 345315370604341,
"firstName": "Sanjeet",
"lastName": "Mohanty",
"displayName": "Sanjeet Mohanty",
"email": "Sanjeet.mohanty#db.com",
"username": "Sanjeet.mohanty#db.com"
}},
"payload": {"messageSent": {"message": {
"messageId": "PyXPTk-6XUBhbONWZ2DOw3___pFykwV5bQ",
"timestamp": 1574330759814,
"message": "<div data-format=\"PresentationML\" data-version=\"2.0\" class=\"wysiwyg\"><p>test 2 <\/p><\/div>",
"data": "{}",
"user": {
"userId": 345315370604341,
"firstName": "Sanjeet",
"lastName": "Mohanty",
"displayName": "Sanjeet Mohanty",
"email": "Sanjeet.mohanty#db.com",
"username": "Sanjeet.mohanty#db.com"
},
"stream": {
"streamId": "cL7jzEDwLxX_gN7D1QbMQn___pP73Ad6dA",
"streamType": "IM"
},
"externalRecipients": false,
"userAgent": "DESKTOP-40.0.0-10726-Windows-7-Chrome-76.0.3809.87",
"originalFormat": "com.symphony.messageml.v2"
}}}
},
{
"id": "Bvua7t",
"messageId": "8usJ_xioHKkRrevhyn38wn___pFykv-WbQ",
"timestamp": 1574330761321,
"type": "MESSAGESENT",
"initiator": {"user": {
"userId": 345315370604341,
"firstName": "Sanjeet",
"lastName": "Mohanty",
"displayName": "Sanjeet Mohanty",
"email": "Sanjeet.mohanty#db.com",
"username": "Sanjeet.mohanty#db.com"
}},
"payload": {"messageSent": {"message": {
"messageId": "8usJ_xioHKkRrevhyn38wn___pFykv-WbQ",
"timestamp": 1574330761321,
"message": "<div data-format=\"PresentationML\" data-version=\"2.0\" class=\"wysiwyg\"><p>test 3<\/p><\/div>",
"data": "{}",
"user": {
"userId": 345315370604341,
"firstName": "Sanjeet",
"lastName": "Mohanty",
"displayName": "Sanjeet Mohanty",
"email": "Sanjeet.mohanty#db.com",
"username": "Sanjeet.mohanty#db.com"
},
"stream": {
"streamId": "cL7jzEDwLxX_gN7D1QbMQn___pP73Ad6dA",
"streamType": "IM"
},
"externalRecipients": false,
"userAgent": "DESKTOP-40.0.0-10726-Windows-7-Chrome-76.0.3809.87",
"originalFormat": "com.symphony.messageml.v2"
}}}
}
]
there is a lot of Liberaiyes to serialize deserialize JSON.
if you have Pojo class match the return value from your rest API
you could use for instance Jackson to do the job
PojoClass mypojo = new ObjectMapper().readValue(JsonString, PojoClass.class);
OR simply converted to JSonNode and iterate over the Nodes
JsonNode jsonNode = new ObjectMapper().readTree(JsonString);
check the link for more info
https://www.baeldung.com/jackson-object-mapper-tutorial

Microsoft-Graph API how to send multi-date event

I have a Java application that uses Microsoft Graph API to send mails and schedule events. I'm able to create an event posting a request with a JSON in the following format:
{
"subject": "Test event",
"start": {
"dateTime": "2017-12-01T09:00:00",
"timeZone": "SA Western Standard Time"
},
"end": {
"dateTime": "2017-12-01T10:00:00",
"timeZone": "SA Western Standard Time"
},
"body": {
"contentType": "TEXT",
"content": "This is a test"
},
"attendees": [{
"emailAddress": {
"address": "someuser#somewhere.com",
"name": "someuser"
}
}]
}
This creates an event on 12-01-2017 from 9:00 AM - 10:00 AM. That's enough when the event is for a single day. But now I need to create a multi-date event that occurs on 12-01-2017 and on 12-02-2017, both dates from 9:00 AM to 10:00 PM. So my question is, what would be the JSON representation needed to create this event?
You need to set a recurrence pattern for the event:
"recurrence": {
"pattern": {
"type": "daily",
"interval": 1
},
"range": {
"type": "endDate",
"startDate": "2017-12-01",
"endDate": "2017-12-01"
}
}
The complete payload would look something like this:
{
"subject": "Test event",
"start": {
"dateTime": "2017-12-01T09:00:00",
"timeZone": "SA Western Standard Time"
},
"end": {
"dateTime": "2017-12-01T10:00:00",
"timeZone": "SA Western Standard Time"
},
"body": {
"contentType": "TEXT",
"content": "This is a test"
},
"attendees": [{
"emailAddress": {
"address": "someuser#somewhere.com",
"name": "someuser"
}
}],
"recurrence": {
"pattern": {
"type": "daily",
"interval": 1
},
"range": {
"type": "endDate",
"startDate": "2017-12-01",
"endDate": "2017-12-01"
}
}
}

How to parse a DiagnosticReport from a JSON and print the same JSON again?

I'm parsing a DiagnosticReport from a JSON file and It works fine, but when I try to print the same JSON file throught IParser encode function, the JSON is different to the original. I need to print the same JSON.
Original JSON (String json)
{
"resourceType": "DiagnosticReport",
"text": {
"status": "generated",
"div": "<div><p><b>Narrative A</b></p></div>"
},
"contained": [
{
"resourceType": "Patient",
"id": "1"
},
{
"resourceType": "Observation",
"id": "2",
"meta": {
"lastUpdated": "2017-03-22T22:00:28.089-05:00"
},
"text": {
"div": "<div><p><b>Narrative B</b></p></div>"
},
"comment": "a comment"
}
],
"status": "appended",
"code": {
"coding": [
{
"code": "Report01"
}
]
},
"subject": {
"reference": "#1"
},
"effectiveDateTime": "2017-03-22T22:00:28-05:00",
"issued": "2017-03-22T22:00:28.070-05:00",
"result": [
{
"reference": "#2"
}
]
}
First step is parse and the second step is encode and print
DiagnosticReport report = parser.parseResource(DiagnosticReport.class, json);
String encodeJSON = parser.encodeResourceToString(report);
System.out.println(encodeJSON);
And the result is different because the text tag in the Observation is not showed
{
"resourceType": "DiagnosticReport",
"text": {
"status": "generated",
"div": "<div xmlns=\"http://www.w3.org/1999/xhtml\"><p><b>Narrative A</b></p></div>"
},
"contained": [
{
"resourceType": "Patient",
"id": "1"
},
{
"resourceType": "Observation",
"id": "2",
"meta": {
"lastUpdated": "2017-03-22T22:00:28.089-05:00"
},
"comment": "a comment"
}
],
"status": "appended",
"code": {
"coding": [
{
"code": "Report01"
}
]
},
"subject": {
"reference": "#1"
},
"effectiveDateTime": "2017-03-22T22:00:28-05:00",
"issued": "2017-03-22T22:00:28.070-05:00",
"result": [
{
"reference": "#2"
}
]
}
I'm trying this because I have a DiagnosticReport generated by my software and I need print it completely in a JSON file.
Thanks for your help!!
It's not legal to have narrative in a contained resource, nor is it legal to have meta/lastUpdated. There are invariants that prohibit both. Ideally, the parsing software should have thrown an exception, but it's not overly surprising that the serializer has trouble serializing content that's not supposed to be there.
Look at dom-1 and dom-4 in dstu3 or dstu2

Json Format error, ask for array when he already gets one

I have a small issues when I try to parse the below JSON arrays
{
"category": [
{
"id": "1",
"idRef": "1",
"name": "projet",
"products": [
{
"category": "1",
"content": "produit du projet , et sa description",
"id": "5",
"name": "ProdProj",
"price": "10000.0"
},
{
"category": "1",
"content": "application de pokemon potoo",
"id": "7",
"name": "pokedex",
"price": "10000.0"
},
{
"category": "1",
"content": "description du projet n2",
"id": "8",
"name": "projet2",
"price": "100.0"
},
{
"category": "1",
"content": "Construisez de vos reve",
"id": "9",
"name": "Pokedex Dream",
"price": "100.0"
}
]
},
{
"id": "2",
"idRef": "2",
"name": "jeux video",
"products": [
{
"category": "2",
"content": "Description du projet de de tout ce qui suit",
"id": "6",
"name": "Jeux video Project",
"price": "10000.0"
},
{
"category": "2",
"content": "The description pokedex is relouu",
"id": "10",
"name": "thePokedex",
"price": "100.0"
}
]
},
{
"id": "3",
"idRef": "3",
"name": "apps mobil",
"products": [
{
"category": "3",
"content": "description de l'application numéro2",
"id": "11",
"name": "application2",
"price": "100.0"
},
{
"category": "3",
"content": "azerazeraze mobil",
"id": "12",
"name": "azerMobil",
"price": "100.0"
}
]
}
]
}
with this code:
public class GsonFormatter {
private static Gson gson = new GsonBuilder()
.registerTypeAdapter(User.class, new UserDeserializer())
.registerTypeAdapter(Category.class, new CategoryDeserializer())
.registerTypeAdapter(Project.class, new ProjectDeserializer())
.create();
public static Gson getGson() {
return gson;
}
}
And I have this method that makes an error:
"Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2"
Public ArrayList<Category>() {
return GsonFormatter.getGson().fromJson(json,
new TypeToken<List<Category>>() {}.getType());
So I have been trying all night long. But I cannot figure out what is going wrong. This is my first JSON use, so i'm sorry for this stupid question...
The error is telling you that while parsing the JSON and mapping it to your Category class, there was a case where your class is expecting an object, but the JSON is an array.
Looking at your JSON, it's easy to see where that is. You have an array of Category objects. In one of them, products is an object, and in another it's an array:
... \"products\":[{\"category\":\"1\",\"content\":\"Jeux ...
... \"products\":{\"category\":\"3\",\"content\":\"application ...
Edit in response to comments: IMHO, yes, the way the server is producing the JSON is broken. What it appears is that if there is only one product in a category, it returns the single product as an object, but if there are multiple products you get an array of them. Ideally you would want the server to always return an array even when there's only one product.
If you can't get the server changed, what you would need to do is handle this in your deserializer. You'd have to manually check the products field and see if it's an object and convert it to an array for your class.
Your above-mentioned method only apples for get a json array without attributes to be extracted.
My following method is suggested to take a json object with an array associated with.
Gson gson = new Gson();
String jsonOutput = "{ \"array\": [{ \"id\" : \"3\", \"name\" : \"hello_world\" }, { \"id\" : \"2\", \"name\" : \"hello_world\" }] }";
JsonObject root = new JsonParser().parse(jsonOutput).getAsJsonObject();
JsonArray terms = root.getAsJsonArray("array");
//JSONArray cms = jsonObject.getJSONArray("array");
MyModel[] arr = gson.fromJson(terms.toString(), MyModel[].class);

Parsing JSON data in java from Facebook Graph response

Here I have a response from the facebook server that returns the list of albums of a selected user. I want to create an array for all the album names labeled "name" as well as the "link" and "cover_photo" to be ready to processed into a listview
{
"data": [
{
"id": "664462156031",
"from": {
"name": "Nate Ellender",
"id": "68004222"
},
"name": "Mobile Uploads",
"link": "https://www.facebook.com/album.php?fbid=664462156031&id=68004222&aid=2081375",
"cover_photo": "754991180141",
"count": 88,
"type": "mobile",
"created_time": "2012-05-12T00:38:14+0000",
"updated_time": "2013-11-04T20:45:08+0000",
"can_upload": false
},
{
"id": "813288706431",
"from": {
"name": "Nate Ellender",
"id": "68004222"
},
"name": "Bitstrips Photos",
"link": "https://www.facebook.com/album.php?fbid=813288706431&id=68004222&aid=1073741826",
"cover_photo": "813288781281",
"count": 1,
"type": "app",
"created_time": "2013-10-31T21:53:11+0000",
"updated_time": "2013-10-31T21:53:15+0000",
"can_upload": false
},
{
"id": "757384214481",
"from": {
"name": "Nate Ellender",
"id": "68004222"
},
"name": "Galveston Vacation 2013",
"description": "Our trip before joining Air Force",
"link": "https://www.facebook.com/album.php?fbid=757384214481&id=68004222&aid=1073741825",
"cover_photo": "757221350861",
"count": 8,
"type": "normal",
"created_time": "2013-05-15T18:37:19+0000",
"updated_time": "2013-05-15T22:12:52+0000",
"can_upload": false,
"likes": {
"data": [
{
"id": "100002572634186",
"name": "Misty O'Quain"
},
{
"id": "100000582072776",
"name": "Clifford Joyce"
},
{
"id": "1045514613",
"name": "Caity Ellender"
}
],
"paging": {
"cursors": {
"after": "MTA0NTUxNDYxMw==",
"before": "MTAwMDAyNTcyNjM0MTg2"
}
}
}
},
{
"id": "542202136091",
"from": {
"name": "Nate Ellender",
"id": "68004222"
},
"name": "Profile Pictures",
"link": "https://www.facebook.com/album.php?fbid=542202136091&id=68004222&aid=2054735",
"cover_photo": "749743202131",
"count": 20,
"type": "profile",
"created_time": "2010-09-02T04:43:32+0000",
"updated_time": "2013-04-13T13:46:14+0000",
"can_upload": false
},
{
"id": "646032913381",
"from": {
"name": "Nate Ellender",
"id": "68004222"
},
"name": "Cover Photos",
"link": "https://www.facebook.com/album.php?fbid=646032913381&id=68004222&aid=2079483",
"cover_photo": "681058471881",
"count": 2,
"type": "cover",
"created_time": "2012-03-22T00:25:50+0000",
"updated_time": "2012-07-17T15:26:24+0000",
"can_upload": false
},
{
"id": "599115930391",
"from": {
"name": "Nate Ellender",
"id": "68004222"
},
"name": "Timeline Photos",
"link": "https://www.facebook.com/album.php?fbid=599115930391&id=68004222&aid=2073818",
"cover_photo": "599115935381",
"count": 1,
"type": "wall",
"created_time": "2011-10-20T14:25:23+0000",
"updated_time": "2011-10-20T14:25:23+0000",
"can_upload": false
},
{
"id": "551798524851",
"from": {
"name": "Nate Ellender",
"id": "68004222"
},
"name": "My Year - 2010",
"link": "https://www.facebook.com/album.php?fbid=551798524851&id=68004222&aid=2060899",
"cover_photo": "551798544811",
"count": 1,
"type": "normal",
"created_time": "2010-12-19T05:11:51+0000",
"updated_time": "2010-12-19T05:12:14+0000",
"can_upload": false
},
{
"id": "522841060841",
"from": {
"name": "Nate Ellender",
"id": "68004222"
},
"name": "Night Lightnin",
"description": "Always wanted to do this, because lightning is way cooler at night. Perhaps next time I'll be able to refine my methods a little. Read as \"bring tripod so you don't have to prop cam up on roof of car\"",
"location": "Just north of Sulphur",
"link": "https://www.facebook.com/album.php?fbid=522841060841&id=68004222&aid=2036447",
"cover_photo": "522841195571",
"count": 15,
"type": "normal",
"created_time": "2009-09-16T04:38:43+0000",
"updated_time": "2009-09-16T04:42:32+0000",
"can_upload": false
},
{
"id": "513270939441",
"from": {
"name": "Nate Ellender",
"id": "68004222"
},
"name": "The Stuff That Doesn't Make Another Album",
"description": "See title.",
"location": "Good question",
"link": "https://www.facebook.com/album.php?fbid=513270939441&id=68004222&aid=2029083",
"cover_photo": "513271029261",
"count": 9,
"type": "normal",
"created_time": "2009-03-03T06:43:09+0000",
"updated_time": "2009-04-01T02:20:22+0000",
"can_upload": false,
"comments": {
"data": [
{
"id": "513270939441_3444",
"from": {
"name": "Misty Bylsma Royal",
"id": "592607110"
},
"message": "I love how the beautiful lady pile is in the same album as the bull pics. Nice.",
"can_remove": false,
"created_time": "2009-03-03T22:37:18+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "513270939441_3451",
"from": {
"name": "Nate Ellender",
"id": "68004222"
},
"message": "Only because they are both things that i only had a few pictures of.",
"can_remove": false,
"created_time": "2009-03-04T02:46:11+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"cursors": {
"after": "Mg==",
"before": "MQ=="
}
}
}
},
{
"id": "511605661671",
"from": {
"name": "Nate Ellender",
"id": "68004222"
},
"name": "What the...?",
"description": "What's wrong with the rain? It's flaky and piles up on stuff... Did the plants leak something?\n",
"location": "Outside",
"link": "https://www.facebook.com/album.php?fbid=511605661671&id=68004222&aid=2026641",
"cover_photo": "511605681631",
"count": 54,
"type": "normal",
"created_time": "2008-12-11T11:59:27+0000",
"updated_time": "2008-12-13T18:06:00+0000",
"can_upload": false
},
{
"id": "511565886381",
"from": {
"name": "Nate Ellender",
"id": "68004222"
},
"name": "The Christmas Tree Farm",
"description": "An Ellender Tradition",
"location": "Grant",
"link": "https://www.facebook.com/album.php?fbid=511565886381&id=68004222&aid=2026590",
"cover_photo": "511566170811",
"count": 19,
"type": "normal",
"created_time": "2008-12-09T02:38:54+0000",
"updated_time": "2008-12-09T02:55:21+0000",
"can_upload": false
}
],
"paging": {
"cursors": {
"after": "NTExNTY1ODg2Mzgx",
"before": "NjY0NDYyMTU2MDMx"
}
}
}
Also, here is where the json data is returned (response). I will need to start parsing the data under response.
Session.NewPermissionsRequest np = new Session.NewPermissionsRequest(this, "friends_photos");
Session.getActiveSession().requestNewReadPermissions(np);
Request rq = new Request(Session.getActiveSession(), userID + "/albums", null, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
}
});
rq.executeAsync();
Any example would be helpful. I would like to study the code to get a better understanding on parsing json data.
You can get a good example of how to do here: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Basically you have to use JSONObject and JSONArray, that you can get from getJSONObject() and getJSONArray().
Once you're on the good spot, use getJSONString() to get the desired value.
In your case it will be something like this:
JSONObject json = new JSONObject(response)
JSONArray jarray = json.getJSONArray("data");
for(int i = 0; i < jarray.length(); i++){
JSONObject oneAlbum = jarray.getJSONObject(i);
//get your values
oneAlbum.getJSONString("name"); // this will return you the album's name.
}
Hope this will help you.
Try this
Session.NewPermissionsRequest np = new Session.NewPermissionsRequest(this, "friends_photos");
Session.getActiveSession().requestNewReadPermissions(np);
Request rq = new Request(Session.getActiveSession(), userID + "/albums", null, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
JSONArray albumArr = response.getGraphObject().getInnerJSONObject().getJSONArray("data");
for (int i = 0; i < albumArr.length(); i++) {
JSONObject item = albumArr.getJSONObject(i);
System.out.println("id : " + item.getString("id"));
System.out.println("fromName : " + item.getJSONObject("from").getString("name"));
System.out.println("fromid : " + item.getJSONObject("from").getString("id"));
System.out.println("link : " + item.getString("link"));
System.out.println("cover_photo : " + item.getString("cover_photo"));
System.out.println("count : " + item.getString("count"));
System.out.println("created_time : " + item.getString("created_time"));
System.out.println("updated_time : " + item.getString("updated_time"));
System.out.println("can_upload : " + item.getString("can_upload"));
}
}
});
rq.executeAsync();

Categories