Gson - Merge multiple JSONs objects into one JSON - java

I have a case where I need to merge multiple JSONs objects into one JSON.
A single response looks like this:
{"name":"MyName"}
Multiple merged JSON looks like this:
["{\"name\":\"name\"}","{\"name\":\"MyName\"}"]
The problem here is that the child JSONs that I want to include can come either from a Java object or are available as String itself.
MyRequest request = new MyRequest();
request.setName("name");
String singleJson = new Gson().toJson(request);
String fromSomePlaceElse = "{\"name\":\"MyName\"}";;
List<String> list = Lists.newArrayList(singleJson,fromSomePlaceElse);
System.out.println(new Gson().toJson(list));
The above gives me the following output:
["{\"name\":\"name\"}","{\"name\":\"MyName\"}"]
instead of:
[{"name":"MyName"}, {"name":"MyName"}]
I don't want to parse the already existing JSON and do the following:
List<MyRequest> list2 = Lists.newArrayList(request, new Gson().fromJson(fromSomePlaceElse, MyRequest.class));
System.out.println(new Gson().toJson(list2));
Can this be done using Gson ?

Just print it.
List<String> list = Lists.newArrayList(singleJson,fromSomePlaceElse);
System.out.println(list);
Then you can get
[{"name":"name"}, {"name":"MyName"}]

if you want json in form of string,you can directly use ---
new Gson().toJson(yourList, new TypeToken<List<JsonObject>>(){}.getType())

Try the given library to merge any amount of JSON-objects at once. The result can be returned as String or JsonObject (GSON). Please reference the code in this answer.

Related

Convert jsonobject to string by using gson issue

I'm try to convert JsonObject to String by using GSON library. But the result output will have one more layer of parent "map" wrap up the json. Please let me know any wrong i did why the layer of parent "Map" will appear?
i do even try to covert the bean by using new Gson().toJson(bean); but the output result also have one more layer of parent "map" wrap up the json.
Condition i need to fulfil by use
1) Mutable object
2) GSON
3) method might handle other object Type
Maven project using as bellow library:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
Java code bellow(example for understand only not the real code, will using in T):
List<JSONObject> records = new ArrayList <JSONObject> ();
JSONObject bean = new JSONObject();
bean.put("A", "is A");
bean.put("B", "is B lah");
bean.put("C", "is C lah");
bean.put("D", "is D");
records.add(bean);
String JSONBody2 = new Gson().toJson(records);
I expect the output is
[{"D":"is D","A":"is A","B":"is B lah","C":"is C lah"}]
but the actual output is
[{"map":{"D":"is D","A":"is A","B":"is B lah","C":"is C lah"}}]
Actual code is as below
public String Json( String json, List<T> list) {
String JSONBody = new Gson().toJson(list);
}
I need to Serialization by using gson that's why i put the T. but i don't have idea why the "map" is appeared here. as previously it work without Parent "Map" wrap up. (same code and same library just new recreated project but having this issue)
try
String JSONBody2 = record.toString());
will give you [{"A":"is A","B":"is B lah","C":"is C lah","D":"is D"}]
You can get more better understanding of type conversion from this link https://stackoverflow.com/a/27893392/4500099
Although others have already answered it, i would like to highlight one important learning. There are 2 ways to convert JsonObject to string.
One is new Gson().toJson(..) and other is JsonObject.toString().
Although both will produce same results in many cases but if the JsonObject has some string fields containing valid urls or base64 ecoded values, the first method will convert & and = into corresponding utf-8 representative characters which will make your urls and base64 ecoded values corrupted. However, second method keep those values intact.
Use JSONArray instead of List , it will give you the desired output:
JSONArray records = new JSONArray();
JSONObject bean = new JSONObject();
bean.put("A", "is A");
bean.put("B", "is B lah");
bean.put("C", "is C lah");
bean.put("D", "is D");
records.put(bean);
String JSONBody2 = new Gson().toJson(records);
Don't use a JSON Object. Just use Object
List<Object> records = new ArrayList<>();
Map<String, String> bean = new HashMap<>();
bean.put("A", "is A");
bean.put("B", "is B lah");
bean.put("C", "is C lah");
bean.put("D", "is D");
records.add(bean);
String JSONBody2 = new Gson().toJson(records);
System.out.println(JSONBody2);
Output is
[{"A":"is A","B":"is B lah","C":"is C lah","D":"is D"}]
If you look at the implementation of org.json.JSONObject, it internally contains a variable called map where it stores all the data. This is the constructor
public JSONObject() {
this.map = new HashMap<String, Object>();
}
When GSON tries to convert to JSON, it just recursively looks into the object and converts all variables to JSON. So in this case, it converts the internal map, which shows up in the Json output.

create json using Google Gson

I want make json
records":[ {"MON_PRIORITY":"","MON_ICR_ACCNO":"100000010010","MON_REPORT_DATE":"","MON_STATUS":"",
But my json is
{"MON_PRIORITY":"","MON_ICR_ACCNO":"100000010010","MON_REPORT_DATE":"","MON_STATUS":"",
My jsp code is
HashMap jsonRecordval = (HashMap) hshValues.get("jsonRecord");
String json="";
json = new Gson().toJson(jsonRecordval );
Thanks..
What you're getting is the JSON produced by a Hashmap. e.g. {"key":"value"}. Breaking it down piece by what, your desired json is a representation of an object { with a records field "records" that contains an array [ of the contents of your hashmap {"key":"value"}
To do that, it's easiest to create an object with instance variables corresponding to the fields to expected output. Something like
public class JsonRecords {
private final List<HashMap> records = new ArrayList<>;
public JsonRecords(HashMap recordsVal) {
records.add(recordsVal);
}
//Getters and setters
}
Then use it to build your JSON
HashMap jsonRecordval = (HashMap) hshValues.get("jsonRecord");
String json = new Gson().toJson(new JsonRecords(jsonRecordval));

Selecting a subset of JSON properties and values using JSONPath

Given a JSON like:
{
"a":1,
"b":2,
"c":3,
"d":4,
"e":5
}
How can I select out b, d and e to get the following JSON?
{
"b":2,
"d":4,
"e":5
}
I want a JSON object and NOT only 2, 4 and 5 values?
This is what I'm trying with and failing:
$.[b,d,e]
JSONPath is not suitable for what you are trying to achieve: JSONPath is designed to select values and not key-value pairs. What you want could be achieved with Jackson or any JSON parser for Java.
If you want to go for Jackson here's the code that will do the trick:
String json = "{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}";
ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(json);
ObjectNode node = mapper.createObjectNode();
node.set("b", tree.get("b"));
node.set("d", tree.get("d"));
node.set("e", tree.get("e"));
String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node);
Elements must be in single quotes.
$.['b','d','e']
Works fine for JsonPath from com.jayway.jsonpath:json-path:2.4.0
Your json path is correct, while json it self is not. It should be:
{
"a":1,
"b":2,
"c":3,
"d":4,
"e":5
}
BTW there is good online testing resources for these purposes: http://jsonpath.com/
You need to modify your JSON to (as said by Andremoniy)
{
"a":1,
"b":2,
"c":3,
"d":4,
"e":5
}
and to select b,d,e use this
$.b,d,e

how to parse multiple json objects with no name

im having some trouble parsing json. I have json in the format of:
{"blah":"blah","blah":"blah"}
{"blah":"blah","blah":"blah"}
{"blah":"blah","blah":"blah"}
Here is the link to the JSON: http://gerrit.aokp.co/query?format=JSON&q=status:merged&age:1d
I cant make this a jsonobject and iterate over it. I currently have it as a string.
Is there a way to iterate over this? there will be over 500.
I tried making it an array by adding square brackets around it, but it didnt work because i needed to divide them with commas. I cant manipulate this by hand because im getting it from the web. So i tried this.
jsonString = jsonString.replaceAll("}(?!,)", "},");
the reason im adding the negative comma is that sometimes i might have a jsonobject inside of of these objects so I only want to add a comma in front of the '}' without commas.
when i do the replaceall i get this error.
Error in fetching or parsing JSON: java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 1:
}(?!,)
^
What am I doing wrong or is there an easier way to do this that im looking over?
EDIT:
Oh yes, I need to implement this in java because this is in an android app.
here is an example how you can accomplish what you want using Jackson's ObjectMapper.
ObjectMapper om = new ObjectMapper();
try {
List<Object> obj = om.readValue(yourJsonString, new TypeReference<List<Object>> () { });
} catch (IOException e1) {
e1.printStackTrace();
}
Now you will have a list of each of the individual Objects in your JSON string. To take it a step further you could create a POJO for the Object you are parsing.
Something like:
public class MyObject{
private String project;
private String branch;
}
That is just an exmple, you would need to define a property for each json property.
Then you can turn :
List<Object> obj = om.readValue(yourJsonString, new TypeReference<List<Object>> () { });
Into
List<MyObject> obj = om.readValue(yourJsonString, new TypeReference<List<MyObject>> () { });
Hope this helps!
From the link you posted, it looks like there are newlines between objects (and only between objects). If that's right, I'd approach it like this:
String[] items = dataFromWeb.split("\n");
String asJSONArrayString = Arrays.toString(items);
JSONArray jsonArray = new JSONArray(asJSONArrayString);
This splits the data at newlines, then joins it together with commas between elements and brackets around the whole thing.
JSONObject jObject = null;
mJsonString = downloadFileFromInternet(urlString);
jObject = new JSONObject(mJsonString);
This will get you json object.
This is the way to get json array from json object:
JSONArray jsonImageArray = jObject.getJSONArray("your string");

From a given Map to a json string (or JSONObject)

In Java, I've these key/value pairs passed by post (for example):
form_id=undefined
frmb[0][cssClass]=input_text
frmb[0][required]=checked
frmb[0][values]=First Name
frmb[1][cssClass]=input_text
frmb[1][required]=checked
frmb[1][values]=Last Name
frmb[2][cssClass]=textarea
frmb[2][required]=undefined
frmb[2][values]=Bio
frmb[3][cssClass]=checkbox
frmb[3][required]=undefined
frmb[3][title]=What's on your pizza?
frmb[3][values][2][baseline]=undefined
frmb[3][values][2][value]=Extra Cheese
frmb[3][values][3][baselise]=undefined
frmb[3][values][3][value]=Pepperoni
frmb[3][values][4][baseline]=undefined
frmb[3][values][4][value]=Beef
frmb[4][cssClass]=radio
frmb[4][required]=undefined
frmb[4][title]=Do you like pizza?
frmb[4][values][2][baseline]=checked
frmb[4][values][2][value]=Yes
frmb[4][values][3][baseline]=undefined
frmb[4][values][3][value]=No
frmb[5][cssClass]=select
frmb[5][multiple]=checked
frmb[5][required]=checked
frmb[5][title]=Select a pizza type:
frmb[5][values][2][baseline]=checked
frmb[5][values][2][value]=Margherita
frmb[5][values][3][baseline]=undefined
frmb[5][values][3][value]=Napoli
frmb[5][values][4][baseline]=undefined
frmb[5][values][4][value]=Marinara
I've to create the following json:
[{"cssClass":"input_text","required":"checked","values":"First Name"},{"cssClass":"input_text","required":"checked","values":"Last Name"},{"cssClass":"textarea","required":"undefined","values":"Bio"},{"cssClass":"checkbox","required":"undefined","title":"What's on your pizza?","values":{"2":{"value":"Extra Cheese","baseline":"undefined"},"3":{"value":"Pepperoni","baseline":"undefined"},"4":{"value":"Beef","baseline":"undefined"}}},{"cssClass":"radio","required":"undefined","title":"Do you like pizza?","values":{"2":{"value":"Yes","baseline":"checked"},"3":{"value":"No","baseline":"undefined"}}},{"cssClass":"select","required":"checked","multiple":"checked","title":"Select a pizza type:","values":{"2":{"value":"Margherita","baseline":"checked"},"3":{"value":"Napoli","baseline":"undefined"},"4":{"value":"Marinara","baseline":"undefined"}}}]
How could I do?
I don't succeed in parsing the keys, grouping the elements which do part of the same JSONObject.
You can use the Gson library for this. It does not support serializaton of nested maps (I assume your output represents a nested map). You can write a custom serializer/deserializer or create your own serialization method following the instructions in this thread
You can do something like this:
JSONArray jsonItems = new JSONArray();
for (int i = 0; i < frmb.size(); i++) {
JSONObject json = new JSONObject();
json.put("cssClass", frmb[i][cssClass]);
json.put("required",frmb[i][required]);
//put json object to json array
jsonItems.put(json);
}
Check here for more details
I resolved by parsing the keys and by building the JSONObjects with the use of two temporary hashtables.

Categories

Resources