I have a different use case where fields in POJO itself stores JSON data, basically grouping of all data.
Now i want the complete JSON generated from above POJO.
At present i am using this method
private static Gson gson = new Gson();
public static String convertObjectToJSON(Object object) throws Exception {
String jsonResponse = gson.toJson(object);
return jsonResponse;
}
But getting output with escape characters around double quotes like below
{ \"_id\" : 234242, \"name\" : \"carlos\"}
I tried various options in GsonBuilder, but not working.
Basically, i am just grouping multiple JSON data and sending it across.
Could you please do the needful help to get rid of the escape characters around double quotes.
UPDATE:
Question is : I have 3 JSONs and need to combine them into a single JSON and need to pass it to html5 client through Spring MVC. As of now i am added the 3 JSONs into a POJO and trying to convert the same to JSON. Same is explained above.
Thanks & Regards
Venkat
I have tried below sample code and it doesn't have any escape characters around double quotes.
class MyPOJO{
private int _id;
private String name;
// getter & setter
}
String json="{ \"_id\" : 234242, \"name\" : \"carlos\"}";
MyPOJOobj=new Gson().fromJson(json, MyPOJO.class);
System.out.println(new Gson().toJson(obj));
output:
{"_id":234242,"name":"carlos"}
EDIT
If you want to combine 3 JSON string then It will be stored as List of object as illustrated below:
sample code:
String json = "[" +
" { \"_id\" : 1, \"name\" : \"A\"}," +
" { \"_id\" : 2, \"name\" : \"B\"}," +
" { \"_id\" : 3, \"name\" : \"C\"}" +
"]";
Type type = new TypeToken<ArrayList<MyPOJO>>() {}.getType();
ArrayList<MyPOJO> obj = new Gson().fromJson(json, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
output:
[
{
"_id": 1,
"name": "A"
},
{
"_id": 2,
"name": "B"
},
{
"_id": 3,
"name": "C"
}
]
Related
{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "XYZ",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}
I am trying to update the "eventName" field with new String. I tried with the following code, It updates the field but returns only four fields in the json array.
public String modifyJson() throws Exception{
String jsonString = PiplineJson.payload(PiplineJson.filePath());
System.out.println(jsonString);
JSONObject jobject = new JSONObject(jsonString);
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
System.out.println(uu);
return uu;
}
This is what the above code does.
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
I am trying to get the complete json once it updates the eventName filed.
{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}
The problem is the way that you are chaining the operations together. The problem is that you are calling toString() on the result of the put call. The put calls returns the inner JSONObject that it was called on. So you end up serializing the wrong object.
Changing this:
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
to
jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString());
String uu = jobject.toString();
should work.
That's because you are returning the first element you extracted from "places" array. You should return "jobject.toString()" instead.
I have a json string as:
string jsonString = "{"Header":{"ID": "103","DateTime": "2020-07-29 09:14:23.802-4:00 1","PlazaID": "01","Lane": "Lane 20","IPAddr": "192.9.0.123"},"Body": {"EventMsg": "Status: Online","EventNum": "99999"}}";
I am trying to get the value if ID from the above json by using Gson and it gives me NullPointerException. My code:
JsonObject jsonObject = new Gson().fromJson(jsonString, JsonObject.class );
//System.out.println("jsonObject: " + jsonObject.toString());
String _ID = jsonObject.get("ID").getAsString();
I am not sure where the error in my code is. Any help is appreciated.
Edit:
As per #Arvind's suggestion, I tried his code and am getting this error:
As per #Arvind's suggestion, this works:
String _ID = jsonObject.get("Header").getAsJsonObject().get("ID").getAsString();
Let's prettify your jsonString first for clarity:
{
"Header": {
"ID": "103",
"DateTime": "2020-07-29 09:14:23.802-4:00 1",
"PlazaID": "01",
"Lane": "Lane 20",
"IPAddr": "192.9.0.123"
},
"Body": {
"EventMsg": "Status: Online",
"EventNum": "99999"
}
}
Notice that "ID" is inside "Header", so you'd have to parse it this way:
String _ID = jsonObject.getJsonObject("Header").get("ID").getAsString();
Also, avoid using get() since there are better convenience methods:
String _ID = jsonObject.getJsonObject("Header").getString("ID");
How to convert a JsonArrayString to List<String> or String[]? I tried to use Gson to covert it, but I failed. Maybe I overlooked some existing methods which can do this? Any other better way to make it or can someone give me some tips?
[
{
"test": "test"
},
{
"test": "test"
},
{
"test": "test",
"test2": "test2",
"test3": [
{
"test": "test"
},
{
"test": "test"
}
]
}
]
I guess you dont know if the value is a JSONObject or a JSONArray. In thise case you may want to use a Map and a Object as Value like this (not tested).
class Model {
private Map<String, Object> test;
}
Take care that you have to validate if the Value is a JSONArray or a JSONObject using (for example):
if (this.getTest().getValue() instanceof JSONObject.class) { ... }
I Finally find the way to resovel:
// Converting JSON String array to Java String array
String jsonStringArray = "[{\"test\":\"test1\"},{\"test\":\"test2\"},{\"test\":\"test3\",\"test2\":[{\"test\":\"test1\"},{\"test\":\"test2\"}]}]";
// creating Gson instance to convert JSON array to Java array
Gson converter = new Gson();
Type type = new TypeToken<List>() {
}.getType();
List list = converter.fromJson(jsonStringArray, type);
// convert List to Array in Java
System.out.println("Java List created from JSON String Array - example");
System.out.println("JSON String Array : " + jsonStringArray);
System.out.println("Java List : " + list);
// let's now convert Java array to JSON array -
String toJson = converter.toJson(list);
System.out.println("Json array created from Java List : " + toJson);
output:
Java List created from JSON String Array - example
JSON String Array : [{"test":"test1"},{"test":"test2"},
{"test":"test3","test2":[{"test":"test1"},{"test":"test2"}]}]
Java List : [{test=test1}, {test=test2}, {test=test3, test2=[{test=test1}, {test=test2}]}]
Json array created from Java List : [{"test":"test1"},{"test":"test2"},{"test":"test3","test2":[{"test":"test1"},{"test":"test2"}]}]
I want to generate a JSON String in the following structure using Jackson API (JsonFactory,JsonGenerator). How can i do it ?
Expected:
{
"api": {
"Salutaion": "Mr",
"name": "X"
},
"additional": {
"Hello",
"World"
}
}
Actual:
{
"api": "{
\"Salutaion\": \"Mr\",
\"name\": \"X\"
}",
"additional": "{
\"Hello\",
\"World\"
}"
}
The values of the attributes api & additional will be available to me as String. Should i be using writeObjectField (as follows) ?
jGenerator.writeObjectField("api", apiString);
After constructing the jGenerator object, how do i get the final constructed JSON Object's String representation ?
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonGenerator jGenerator = jfactory.createJsonGenerator(outputStream);
jGenerator.writeStartObject();
jGenerator.writeObjectField("api", apiString);
jGenerator.writeObjectField("additional", additionalString);
jGenerator.writeEndObject();
jGenerator.close();
outputStream.close();
outputStream.toString()
The outputStream.toString() gives a json string but the double quotes (") in the apiString are getting prefixed with an escape character \
Is this the right way ?
Assuming apiString and additionalString are references to String objects with JSON content, you'll want to write them raw, ie. their content directly. Otherwise, you're serializing them as JSON strings and Jackson will need to escape any relevant characters.
For example
jGenerator.writeFieldName("api");
jGenerator.writeRawValue(apiString);
for api, and the same for additional.
{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
This is how my Json file looks .I m required to convert this json to a csv .(I m trying to convert a multi-dimesional data to 2d).I m using gson for my purpose.I cannot use gson.fromgson() function to object map with a template because it should be generic .
I know we can use CDL to convert jsonarray to csv format but It wont work in my case .
my csv format looks like
Employee*
empMID,comment.$,contact.address,contact.freetext,gender
mock:1,,2400 waterview,TRUE,male
mock:123,,2200 waterview,TRUE,female
colA#
TRUE
colB#
FALSE
I tried using google-GSON api to convert to this format .But I m not able to convert to this format .I have used * to represent its a json array and # to represent its a primitive type and contact.address to represent nested array inside another json array .I having problem relating this nested structure .I m able to traverse everything recursively like a column. Thanks in advance
public static void main(String[] args) throws IOException{
BufferedReader reader=null;
StringBuilder content=null;
String result=null;
reader = new BufferedReader(new FileReader("temp.json"));
String line = null;
content= new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
result= content.toString();
JsonElement jelement = new JsonParser().parse(result);
printJsonRecursive(jelement);
}
public static void printJsonRecursive(JsonElement jelement){
if(jelement.isJsonPrimitive()){
System.out.println(jelement.getAsString());
return;
}
if(jelement.isJsonArray()){
JsonArray jarray= jelement.getAsJsonArray();
for(int i=0;i<jarray.size();i++){
JsonElement element= jarray.get(i);
printJsonRecursive(element);
}
return;
}
JsonObject jobject= jelement.getAsJsonObject();
Set<Entry<String, JsonElement>> set= jobject.entrySet();
for (Entry<String, JsonElement> s : set) {
printJsonRecursive(s.getValue());
}
}
}
You can achieve this thru reflection if you have a object mapped to the json.
use gson/jackson to convert json to java object
append fields using reflection by iterating the class and get any field you interested in.
append value with reflection by getting value from the target object.
More detail look at my blog post below:
vcfvct.wordpress.com/2015/06/30/converting-nested-json-files-to-csv-in-java-with-reflection/
You are not printing the key. This should fix it.
for (Entry<String, JsonElement> s : set) {
System.out.println(s.getKey()); //Added
printJsonRecursive(s.getValue());
}
You can take care of \ns from here.
EDIT
If you want to print the keys just once for repeating json objects, create a Java bean to hold the data and populate it during your recursion. Once the bean is complete, add a method there to print all the data in the format you want (printing keys only once and so on).
You can use the library json2flat for converting your JSON to CSV.
This library doesn't require any POJO's. It simply takes your JSON as string and returns a 2D representation of it in the format of List<Object[]>.
For example for the JSON:
{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
It gives an output:
/cola,/colb,/Employee/empMID,/Employee/col1,/Employee/gender,/Employee/contact/address,/Employee/contact/freetext
,,"mock:1","something",,"2400 waterview",true
,,"mock:2","something",,"2200 waterview",true
false,false,,,,,
/**
* Get separated comlumns used a separator (comma, semi column, tab).
*
* #param headers The CSV headers
* #param map Map of key-value pairs contains the header and the value
*
* #return a string composed of columns separated by a specific separator.
*/
private static String getSeperatedColumns(Set<String> headers, Map<String, String> map, String separator) {
List<String> items = new ArrayList<String>();
for (String header : headers) {
String value = map.get(header) == null ? "" : map.get(header).replaceAll("[\\,\\;\\r\\n\\t\\s]+", " ");
items.add(value);
}
return StringUtils.join(items.toArray(), separator);
}