This question already has answers here:
Merge/Extend JSON Objects using Gson in Java
(4 answers)
Closed 1 year ago.
Given this JSON:
{
"contact_data": [
"address/all",
"telephone/us"
],
"financial_data": [
"bank_account_number/all",
"bank_account_number/uk",
"credit_card_numbers"
]
}
and this JSON:
{
"financial_data": [
"credit_card_numbers",
"bank_account_number/ca",
"bank_account_number/all"
],
"government_id": [
"driving_license/americas"
],
"sensitive_data": [
"racial_ethnic_origin"
]
}
I want to merge these to look like this:
{
"contact_data": [
"address/all",
"telephone/us"
],
"financial_data": [
"credit_card_numbers",
"bank_account_number/ca",
"bank_account_number/uk",
"bank_account_number/all"
],
"government_id": [
"driving_license/americas"
],
"sensitive_data": [
"racial_ethnic_origin"
]
}
I have the following, which almost works:
import org.json.JSONObject;
...
final List<String> jsonStrings = ...; // A list of the above sample JSONs
final List<JSONObject> jsonObjects = jsonStrings
.stream()
.map(JSONObject::new)
// JSONObject.getNames() (called later on) will return null if JSONObject is empty, so filter out empty objects.
.filter(jsonObject -> !jsonObject.isEmpty())
.collect(Collectors.toList());
if (jsonObjects..size() > 1) {
// Merge multiple JSONObjects: https://stackoverflow.com/a/2403453/12177456
final JSONObject firstJsonObject = jsonObjects.get(0);
final JSONObject merged = new JSONObject(firstJsonObject, JSONObject.getNames(firstJsonObject));
final List<JSONObject> remainingJsonObjects = jsonObjects.subList(1, jsonObjects.size());
for (final JSONObject nextJsonObject : remainingJsonObjects) {
for (final String nextJsonObjectFieldName : JSONObject.getNames(nextJsonObject)) {
merged.put(nextJsonObjectFieldName, nextJsonObject.get(nextJsonObjectFieldName));
}
}
return merged;
}
however, where I would expect to see 4 entries in financial_data:
...
"financial_data": [
"bank_account_number/all",
"bank_account_number/uk",
"bank_account_number/ca",
"credit_card_numbers"
]
...
instead, I see just 3, with bank_account_number/uk not in the merged result:
...
"financial_data": [
"bank_account_number/all",
"bank_account_number/ca",
"credit_card_numbers"
]
...
I'm not stuck on using org.json, if it's simplier using gson, jackson, plain Java maps, I'm ok with that.
Actually, it won't work. The problem is here:
merged.put(nextJsonObjectFieldName, nextJsonObject.get(nextJsonObjectFieldName))
This replaces the entry with key nextJsonObjectFieldName with the later one. That is why you're getting in the financial_data from the second object.
{
"financial_data": [
"credit_card_numbers",
"bank_account_number/ca",
"bank_account_number/all"
]
}
You are seeing other keys okay because other keys hase exact same value in both JSON's. If you change the value of other keys too in the second json, you'll see it the merged JSON will have the values with the same key from second json. That is, IT WON'T WORK.
What you can do is, you can check if the key has already value in the map or not. If there's no existing JSONobject for this key, just put it into the merged as you're doing. Otherwise, we have some more job to do:
JSONObject jsonObject = merged.get(nextJsonObjectFieldName);
if (jsonObject != null) {
final JSONObject finalObj = mergeJsonObjectCheckingFieldValues(jsonObject, nextJsonObject.get(nextJsonObjectFieldName));
merged.put(nextJsonObjectFieldName, finalObj);
} else {
merged.put(nextJsonObjectFieldName, nextJsonObject.get(nextJsonObjectFieldName));
}
The mergeJsonObjectCheckingFieldValues method checks each element between the given two JSONObject and compares whether they are same. As per your example and for simply answering this question, I've assumed that each of the JSONObject is nothing but a list of String. For this, we'll be needing objectMapper. So make sure you have the com.fasterxml.jackson.databind.ObjectMapper in your project. So, the checking will be:
ObjectMapper mapper = new ObjectMapper();
public JSONObject mergeJsonObjectCheckingFieldValues(JSONObject jsonObject, JSONObject nextJsonObject)) {
List<String> existingList = Arrays.asList(mapper
.readValue(jsonObject.toString(), String[].class));
List<String> newList = Arrays.asList(mapper
.readValue(nextJsonObject.toString(), String[].class));
List<String> toBeAdded = newList
.stream()
.filter(x -> !existingList.contains(x))
.collect(Collectors.toList());
if(toBeAdded.size() > 0) {
existingList.addAll(toBeAdded);
}
return new JSONObject(JSONArray.toJSONString(existingList));
}
This is the probable solution to your problem. I haven't tested it, but the code should be pretty much this.
I went with the accepted answer here using gson:
https://stackoverflow.com/a/34092374/12177456
Handles recursively merging JsonObjects
Handles conflicts when the key exists in both maps
Has special handling for non-primitive values such as Arrays
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 2 years ago.
I'm just getting started with using json with java. I'm not sure how to access string values within a JSONArray. For instance, my json looks like this:
"media": {
"images": [
"https://newstaging-api.safegold.com"
],
"videos": [
"https://newstaging-api.safegold.com"
]
}
Now I want to get the value of "images".Actually I want show image in ImageView from URL.
Thanks in advance
JSONObject json = new JSONObject(json_data); //json_data - your json string
JSONObject media = json.getJSONObject("media");
JSONArray images = media.getJSONArray("images");
String link = images.getString(0);```
This question already has answers here:
How can I convert JSON to a HashMap using Gson?
(16 answers)
Closed 5 years ago.
I have a problem trying to parse a json file to JSON object
My JSON File is under the form :
{ "objectJSON": [
{
"attribute":"value",
"attribute":"value",
"attribute":"value",
"attributes" :{
"att1": "val1",
"att2":"val2",
"att3":"val3",
// more atts and vals may figure here !
}
},
{
"attribute":"value",
"attribute":"value",
"attribute":"value",
"attributes" :{
"att1": "val1",
"att2":"val2",
"att3":"val3",
// more atts and vals may figure here !
}
}
]
}
my problem is that the object "attributes" has an unknown number of arguments so I can not create a class for it , I thought about using a
map<String,String> attributes;
but I don't know how to parse it from the file especially that I want to keep my class "ObjectJSON" witch represents the root of my file.
I'm using gson of google
thanks in advance .
Using org.json library:
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I am trying to parse JSON data which is like:
{
"name1": "xyz",
"data":[{
"education": {
"School": "xyz",
"ug": "xyz",
"Activities": [{
...
}],
"Prizes": [{
...
}],
"Curriculum":[{
...
}]
}
}]
}
How can I fetch the JSONArray of activities, prizes, curriculum values?
If you just want the values of the first element (you are looking at an array so you may want all the elements) you can try this:
String src = " { ... } "; //your json
JSONObject mainObject= new JSONObject(src);
JSONArray dataArray= mainObject.getJSONArray("data");
JSONObject firstDataObject = dataArray.getJSONObject(0); //get the first element
JSONObject educationObject = firstDataObject.getJSONObject("education");
JSONArray activitiesArray = educationObject.getJSONArray("Activities");
//do something with the array. Ex: activitiesArray.getJSONObject(0);
JSONArray prizesArray = educationObject.getJSONArray("Prizes");
//do something with the array
JSONArray curriculumArray = educationObject.getJSONArray("Curriculum");
//do something with the array
This question already has answers here:
How do I parse a JSONArray in Java with Json.simple?
(3 answers)
Closed 7 years ago.
Trying to use json simple to parse data from rest service. The response looks like:
{
"locations": [
"city" : "San Jose",
"state" : "Ca",
"job" : {
"site" : "Main Processing",
"region" : "USA"
}
]
}
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray array = (JSONArray) jsonObject.get("locations");
for(int i = 0; i < array.size(); i++) {
String site = array.getJSONObject(i).getString("site");
}
My issue is I am having trouble getting a reference to the job element from JSONArray object. The "locations" reference is basic parsing but the "job" reference is giving me issue when its defined inside an array.
Also getJSONObject does not seem to be a valid method to JSONArray.
Can this be done with the json-simple library?
The getJSONObject method is provided by the org.json.JSONArray class. (without using json-simple). I can not find it in the json-simple doc. So using the org.json.* package import, you can do:
JSONObject jsonObject = new JSONObject(jsonAsString);
JSONArray array = jsonObject.getJSONArray("locations");
//You should check that array.length() >= 3
JSONObject job = array.getJSONObject(2);
String site = job.getString("site");