Retrieve the required JSON object from JSON response - java

I am trying to connect to a remote service to receive some JSON data. I would like to model the JSON in an efficient way so that I can deserialise it to a corresponding Java class model.
Say that the JSON I receive is of the format
{
{
"name" : "abc",
"age" : 54,
"gender" : "m",
},
{
"name" : "def",
"age" : 45,
"gender" : "m",
},
{
"name" : "der",
"age" : 43,
"gender" : "f",
},
}
Here are my questions
Is there any way to get the details of a person (say name = "abc") without Iterating over the response ?
If not can you suggest any other JSON format which enables us to quickly access any value
from the response without Iterating.
If Iterating is the only way, then could you also suggest the effective way to model the class and the JSON

Related

Combine Two Json Objects in java which is in single json array

I have one Json array which is consist 2 or 3 json objects, now I need to combine both the json objects into single json object, 1st json object is coming from one method 2nd is coming from another method let me explain with example
response[
{
"id" : 1,
"name" : "Hi",
"no.of slots" [
{
"Mrng" : 10:30,
"Evening" : 11:20
},
{
"Mrng" : 12:00,
"Evening" : 4:00
}
]
},
{
"email" : "abc#gmail.com",
"address" : "abc district"
"no.of slots" [
{
"Mrng" : 10:30,
"Evening" : 11:20
}
]
}
]
then I need output like
response: {
"id" : 1,
"name" : "Hi",
"no.of slots" [
{
"Mrng" : 10:30,
"Evening" : 11:20
},
{
"Mrng" : 12:00,
"Evening" : 4:00
}
],
"email" : "abc#gmail.com",
"address" : "abc district"
}
In no of slots If I have duplicates need to remove or if unique need to combine, any help will be appreciate.
Thanks in advance
You can have a class representing Mrng and Evening properties and override that class's equals and hash methods for comparing for these attributes. Then have a Set and generate instances and put elements to this.
Finally you will get a unique list and have a json string with some little research. This should be done to no.of.slots only

How to set the values for JSONPath Syntax dynamically?

This is the JSON:-
{
"firstName": "John",
"lastName" : "doe",
"age" : 26,
"address" : {
"streetAddress": "naist street",
"city" : "Nara",
"postalCode" : "630-0192"
},
"phoneNumbers": [
{
"date" : "2018-10-09",
"number": "0123-4567-8888"
},
{
"type" : "2018-10-12",
"number": "0123-4567-8910"
}
]
}
And below is the JSONPath syntax to fetch the "number":-
$.phoneNumbers[?(#.date=="2018-10-09")].number
I want to change the date value to future dates. For example my above syntax should look like this after changing the date:-
Increased date for next 2 months.
$.phoneNumbers[?(#.date=="2018-12-09")].number
Can we do it using groovy? I ant to automate it, Since, I have lot many JSONPath syntax. So, it'll be really tedious task to change each and every date manually.

Spring Data Tool Suite - Bulk Insert of objects

I am developing an API that create a list of Questions , and would like to know check if STS have any native capability that can support bulk insert , or if i have to create a custom query using #Query annotation?
I have refer to this Spring Data MongoDB support bulk insert/save , i would like to check if an unique ObjectId still be generated through bulk insert/save?
Sample definition i am expecting , where each question is differentiated with an unique Id.
questions": [
{
"id" : "01-QuestionId",
"type" : "multiple",
"question" : "What is your Gender?",
"options" : [
{
"key" : "a",
"value" : "Male"
},
{
"key" : "b",
"value" : "Female"
}
],
"survey":{
"id": "123",
"name": "Test1",
"description": "First Survey"
}
},
{
"id" : "02-QuestionId",
"type" : "multiple",
"question" : "What is your income?",
"options" : [
{
"key" : "a",
"value" : "1000"
},
{
"key" : "b",
"value" : "2000"
}
],
"survey":{
"id": "123",
"name": "Test1",
"description": "First Survey"
}
}
]
Thanks all!
Robin
Found out after deeper research in Spring Data.
We can just use save() or insert() interface from MongoRepository class.
For example
final List savedQuestions = questionRepository.save(questions);

Retrieving values from nested JSON using GSON

I'm working with JSON for the first time and my goal is to make an object with the properties Destination, Origin, and Duration from this JSON result (Google Distance Matrix API)
{
"destination_addresses" : [ "123 High St, Los Angeles, CA 90210, USA" ],
"origin_addresses" : [ "800 Lake Dr, Los Angeles, CA 90210, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "2.0 km",
"value" : 1969
},
"duration" : {
"text" : "6 mins",
"value" : 338
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
So far I have been able to correctly store destination and origin using this line
Property data = new Gson().fromJson(json, Property.class);
But I am having a very hard time figuring out how to get the values from inside the nests. Specifically, I'm trying to grab the "text" from duration.
Any help would be greatly apprciated!
First create a container for the surrounding data.
class MainContent
{
public String destination_addresses;
public String bar;
public List<SubContent> subcontent;
}
Then you create a class for the nested data:
class SubContent
{
public String text;
}
The fields in either classes must have the same names as your json object does.
Then simply:
gson.fromJson(jsonData, MainContent.class);
GSON will attempt to reflect the values from the json string into the object.

Build Json Object then relate the results to HTML table data

I pass out a ajax get which contains a parameter i.e. date added to db.
Java queries the DB for results of persons added on this date, and builds a JSON object for me like so:
{
"resultdata" : { "rowsReturned" : "2", "fetchTime" : "180"}
"row_1" : { "name" : "Larry", "sex" : "m", "age" : "26", "location" : "seattle" }
"row_2" : { "name" : "Pedro", "sex" : "m", "age" : "22", "location" : "unknown" }
}
I can then return the JSON object as a String. I'd then like to dynamically build a table based on these results.
First of all is the JSON object correct for building a table?
The result data tells me how many rows and the time taken in milliseconds, followed by however many rows in that particular format.
I then want to create a table inside a specific div element once these results are returned to my browser on the fly with no page refreshes etc.
so Id expect Table headers with titles of each column - followed by you guessed it 2 rows.
How is the best way to go about doing this. I am familiar with jQuery, JSON is totally new to me and dealing with JSON in jQuery is something i'm keen on learning.
Any help is much appreciated.
you can use jsonlint to validate your json.
Yours is not valid. It's missing some ',':
{
"resultdata" : {
"rowsReturned" : "2",
"fetchTime" : "180"
}, // <--
"row_1" : {
"name" : "Larry",
"sex" : "m",
"age" : "26",
"location" : "seattle"
}, // <--
"row_2" : {
"name" : "Pedro",
"sex" : "m",
"age" : "22",
"location" : "unknown"
}
}
I've made a little DEMO of one possible way how to loop through the json with for-in-loops
for (key in json) {
loops through the json and stores each key in the 'key' variable.
in your case 'resultdata','row_1','row_2'.
So to access the data for each key you write json[key] which translates to json['row_1'] for example.
Now you do the same thing for the row_1 object with:
for(key1 in json[key])
key1 are now the keys in the row_1 object: 'name','sex',...
to access the data now you'll write json[key][key1] which would be json['row_1']['name'] for example.
of course it's advisable to give the keys meaningful names to avoid confusion like in my example:)
Your JSON looks fine for building a table.
You'll want to use $.getJSON() to fetch the JSON data, as it will automatically parse the JSON into an object for you. If you need the advanced features of $.ajax(), you can call $.parseJSON() on the returned data from the AJAX call and it will parse the JSON into an object.

Categories

Resources