What is the best way to combine (merge) two JSONObjects?
JSONObject o1 = {
"one": "1",
"two": "2",
"three": "3"
}
JSONObject o2 = {
"four": "4",
"five": "5",
"six": "6"
}
And result of combining o1 and o2 must be
JSONObject result = {
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6"
}
I have your same problem: I can't find the putAll method (and it isn't listed in the official reference page).
So, I don't know if this is the best solution, but surely it works quite well:
//I assume that your two JSONObjects are o1 and o2
JSONObject mergedObj = new JSONObject();
Iterator i1 = o1.keys();
Iterator i2 = o2.keys();
String tmp_key;
while(i1.hasNext()) {
tmp_key = (String) i1.next();
mergedObj.put(tmp_key, o1.get(tmp_key));
}
while(i2.hasNext()) {
tmp_key = (String) i2.next();
mergedObj.put(tmp_key, o2.get(tmp_key));
}
Now, the merged JSONObject is stored in mergedObj
json objects to be merge in that new json object like this.
JSONObject jObj = new JSONObject();
jObj.put("one", "1");
jObj.put("two", "2");
JSONObject jObj2 = new JSONObject();
jObj2.put("three", "3");
jObj2.put("four", "4");
JSONParser p = new JSONParser();
net.minidev.json.JSONObject o1 = (net.minidev.json.JSONObject) p
.parse(jObj.toString());
net.minidev.json.JSONObject o2 = (net.minidev.json.JSONObject) p
.parse(jObj2.toString());
o1.merge(o2);
Log.print(o1.toJSONString());
now o1 will be the merged json object.
you will get the output like this ::
{"three":"3","two":"2","four":"4","one":"1"}
please refer this link and download the smartjson library ..here is the link http://code.google.com/p/json-smart/wiki/MergeSample
hope it will help.
How about this:
Iterator iterator = json2.keys();
while(iterator.hasNext()){
String key = iterator.next().toString();
json1.put(key,map.optJSONObject(key));
}
Merge JsonObject(gson)-
JsonObject data = new JsonObject();
data = receivedJsoData.get("details").getAsJsonObject();
JsonObject data2 = new JsonObject();
data2 = receivedJsoData1.get("details").getAsJsonObject();
JsonObject mergedData = new JsonObject();
Set<Map.Entry<String, JsonElement>> entries = data1.entrySet(); //will return members of your object
for (Map.Entry<String, JsonElement> entry : entries) {
mergedData.add(entry.getKey(), entry.getValue());
}
Set<Map.Entry<String, JsonElement>> entries1 = data2.entrySet(); //will return members of your object
for (Map.Entry<String, JsonElement> entry : entries1) {
mergedData.add(entry.getKey(), entry.getValue());
}
Try this.. hope it helps
JSONObject result = new JSONObject();
result.putAll(o1);
result.putAll(O2);
Related
ArrayList entries, and this entries is of LinkedHashMap type, I want to convert this into jsonOject for the use, how can I do this?
for(Object entry : entries){
JSONObject entryToProcess = (JSONObject) entry;
}
Hi this conversion utility should do.
What happens here is that you call the method .getKeys() on the LinkedHashMap object to get all the keys. Then for each key you retrieve the information from the LinkedHashMap and you put it inside the JSONObject
// Your input LinkedHashMap
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();
// Providing general values for the test
linkedHashMap.put("First key", "First value");
linkedHashMap.put("Second key", "Second value");
linkedHashMap.put("Third key", "Third value");
// Initialization of the JSONObject
JSONObject jsonObject = new JSONObject();
// for-each key in the LinkedHashMap get the value and put both of
// them into the JSON
for (String key : linkedHashMap.keySet()) {
jsonObject.put(key, linkedHashMap.get(key));
}
The part you care about should be the for loop.
Cheers,
Simple JSONObject constructor would do the trick
for(Object entry : entries){
JSONObject entryToProcess = new JSONObject((LinkedHashMap)entry);
}
Sample:
LinkedHashMap<String,Object> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("A",1);
linkedHashMap.put("some key","some value");
Map<String, String> someMap = new HashMap<>();
someMap.put("map-key-1","map-value-1");
someMap.put("map-key-2","map-value-2");
linkedHashMap.put("another key",someMap);
JSONObject jsonObject = new JSONObject(linkedHashMap);
System.out.println(jsonObject.toJSONString());
Output:
{
"another key": {
"map-key-1": "map-value-1",
"map-key-2": "map-value-2"
},
"A": 1,
"some key": "some value"
}
I have a JsonElement:
JsonElement testCaseParametersJson = batchItem.getTestCase().getToolParameters().get("testCaseParameters");
of which assigns the following:
["dessert", "place", "tvShow"]
And I have a JsonArray:
JsonObject testParametersJson = batchItem.getTestParameters().getAsJsonObject();
of which assigns the following:
{"dessert": "cookies", "tvShow": "survivor", "color" : "blue"}
I'd appreciate some advice on how to check if the key in the JsonArray exists as an item in the JsonElement.
Using Gson library, you can get the String values from your JSONElement / JSONObject and do the following:
String jsonObject = "{\"dessert\": \"cookies\", \"tvShow\": \"survivor\", \"color\" : \"blue\"}";
String jsonArray = "[\"dessert\", \"place\", \"tvShow\"]";
Map<String, String> objMap = new Gson().fromJson(jsonObject, new TypeToken<HashMap<String, String>>() {}.getType());
List<String> arrayVals = new Gson().fromJson(jsonArray, new TypeToken<List<String>>(){}.getType());
for(Entry<String, String> entry : objMap.entrySet()) {
for (String val : arrayVals) {
if (entry.getKey().equals(val)) {
System.out.println("Found value in key set: " + val);
}
}
}
Code can be summarized, and if using Java 8, you can try "forEach" loop according to your needs.
This is very simple one but struggeling. help me out of this.
I am having a json data { "abc":"test","bed":"cot","help":"me"}
I want to convert above jsonObject into JSON ARRAY like [{ "abc":"test","bed":"cot","help":"me"}]
JSONObject obj= new JSONObject(str.toString());
Iterator x = obj.keys();
JSONArray jsonArray = new JSONArray();
Map<String, String> map = new HashMap<String, String>();
while (x.hasNext()) {
for(int i=0;i<obj.length();i++) {
LOG.info("=============");
String key = (String) x.next();
jsonArray.put(obj.get(key));
}
}
I am getting only values. Please help me solve this.
Directly put JsonObject i.e. obj into jsonArray
jsonArray.put(obj);
//result is [{ "abc":"test","bed":"cot","help":"me"}]
Final code
JSONObject obj= new JSONObject(str);
JSONArray jsonArray = new JSONArray();
//simply put obj into jsonArray
jsonArray.put(obj);
//result is [{ "abc":"test","bed":"cot","help":"me"}]
It works for me.
JSONObject obj = new JSONObject(result.toString());
JSONArray arr = obj.getJSONArray("value");
I have a json file like this:
{
"list": [
{
"ID" : "1",
"value" : "value is one"
}
{
"ID" : "2",
"value" : "value is two"
}
{
"ID" : "3",
"value" : "value is three"
}
{
"ID" : "4",
"value" : "value is four"
}
]
}
what I want to do is read the josn file and returns the message based on the ID i specify. So for example
if (this.list.containsKey("1"))
{
return this.list.get(messageTitle);
}
That's what I tried but it returns all the values and ID.
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("jsonFile.json"));
JSONObject jsonObject = (JSONObject) obj;
// loop array
JSONArray msg = (JSONArray) jsonObject.get("list");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
How try like this,
JSONArray msg = (JSONArray) jsonObject.get("list");
for(int i = 0;i < msg.length();i++ ) {
JSONObject jsonObj = msg.getJSONObject(i);
//now get id & value
int id = jsonObj.getInt("ID");
String value = jsonObj.getString("value");
if (1 == id) {
//now 'value' is what you want
System.out.println(value);
}
}
Note: can break the loop when the result is satisfied.
You can try with TypeReference using ObjectMapper to convert it into appropriate Map object.
sample code:
BufferedReader reader = new BufferedReader(new FileReader(new File("jsonFile.json")));
TypeReference<Map<String, ArrayList<Map<String, String>>>> typeRef = new TypeReference<Map<String, ArrayList<Map<String, String>>>>() {};
ObjectMapper mapper = new ObjectMapper();
try {
Map<String, ArrayList<Map<String, String>>> data = mapper.readValue(reader, typeRef);
ArrayList<Map<String, String>> list = data.get("list");
for (Map<String, String> map : list) {
if (map.get("ID").equals("1")) {
System.out.println(map.get("value"));
}
}
} catch (Exception e) {
System.out.println("There might be some issue with the JSON string");
}
output:
value is one
I have got a Map with a key and a list of JSONObjects as shown
Map<String, LinkedList<JSONObject>> vendorOrdersMap = new LinkedHashMap<String, LinkedList<JSONObject>>();
I need to calculate price present under each LinkedList of a Vendor , to know which vendor has got the highest price .
Map<String, LinkedList<JSONObject>> vendorOrdersMap = new LinkedHashMap<String, LinkedList<JSONObject>>();
// For Vendor 1
JSONObject vendor1 = new JSONObject();
vendor1.put("price", "100");
JSONObject vendor2 = new JSONObject();
vendor2.put("price", "200");
LinkedList<JSONObject> list1vendor1 = new LinkedList<JSONObject>();
list1vendor1.add(vendor1);
list1vendor1.add(vendor2);
// For Vendor2
JSONObject vendor3 = new JSONObject();
vendor1.put("price", "200");
JSONObject vendor4 = new JSONObject();
vendor2.put("price", "300");
LinkedList<JSONObject> list1vendor2 = new LinkedList<JSONObject>();
list1vendor2.add(vendor3);
list1vendor2.add(vendor4);
// Add them to the Map
vendorOrdersMap.put("Vendor1", list1vendor1);
vendorOrdersMap.put("Vendor2", list1vendor2);
//I started with this but couldn't able to proceed further with this
for (Map.Entry<String, LinkedList<JSONObject>> entry : vendorOrdersMap.entrySet())
{
String key = entry.getKey();
LinkedList<JSONObject> jsonobj = entry.getValue();
}
Your last line was:
LinkedList<JSONObject> jsonobj = entry.getValue();
After this, iterate over list again like:
for(JSONObject obj : jsonobj) {
Then get values out of JSONObject like:
String price = obj.getString("price");
Then do your comparison to calculate highest price.