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"}]}]
Related
{
"Object1": {
"description": "An object",
"data": "more data"
},
"Object2": {
"description": "An object",
"data": "more data"
}
}
How would I use GSON to iterate over the elements in this JSON Object to easily parse each element one by one?
Yes there is, but PrabhakarP is right, associative arrays in JSON are objects. So in your case,
{
"Object1": {
"description": "An object",
"data": "more data"
}
}
You would have a meta-object containing each array element as a property, which doesn't really make sense. You should parse it differently.
But if you still need, in GSON, then try ,
JsonArray body = gson.fromJson(yourString, JsonArray.class);
JSONObject metaObj = new JSONObject();
for (JsonElement currEle : paymentsArray) {
JSONObject currObj = currEle.getAsJsonObject();
String nameVal = currObj.get("name");
currObj.remove("name");
metaObj.addProperty(nameVal, currObj);
}
I would suggest you to add a property to each object in array and use it
I looked at the man page and found I could loop over the set of members in the object.
JsonObject obj = gson.fromJson(jsonFile, JsonObject.class);
for(Map.Entry<String, JsonElement> element : obj.entrySet()) {
Object obj = gson.fromJson(element.getValue(), Object.class);
// do stuff with the object
}
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"
}
]
I hope someone can show me where i'm doing it wrong...
I'm using sendgrid for my email tracking and it is posting a JSON like the following:
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com"
"userid": "1123",
"template": "welcome"
}
]
Now i want to get the value of for example for "timestamp" which is 1337966815 . I've tried the following:
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
String jsonString = jb.toString();
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
String timeStam = jsonObject.get(timestamp).toString();
The string of jsonString gives me the following which i think is in the right format:
[ { "email": "john.doe#sendgrid.com", "timestamp": 1337966815, "event": "click", "url": "http://sendgrid.com" "userid": "1123", "template": "welcome" }]
But i'm getting the following error at this line of code - JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 52
What am I doing wrong? Is it the format of jsonString that is confusing the JsonObject?
Any help would be very much appreciated.
Kind regards
Francois
The JSON you show in both examples is invalid. There is a comma missing after "url":"http://sendgrid.com"
Ignoring that, the JSON you show is an array of JSON objects, not an object. This is what the [] denotes (correcting the missing comma):
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com",
"userid": "1123",
"template": "welcome"
}
]
If you are not mapping this JSON to a Java POJO, then you would want to use Gson's JsonParser to parse your String to a JsonElement (Note you could even use it to parse directly from the Stream, but this if for how you have your code now).
JsonElement je = new JsonParser().parse(jsonString);
Now you have what's called a "parse tree". This JsonElement is the root. To access it as an array you're going to do:
JsonArray myArray = je.getAsJsonArray();
You only show this array containing one object, but let's say it could have more than one. By iterating through the array you can do:
for (JsonElement e : myArray)
{
// Access the element as a JsonObject
JsonObject jo = e.getAsJsonObject();
// Get the `timestamp` element from the object
// since it's a number, we get it as a JsonPrimitive
JsonPrimitive tsPrimitive = jo.getAsJsonPrimitive("timestamp");
// get the primitive as a Java long
long timestamp = tsPrimitive.getAsLong();
System.out.println("Timestamp: " + timestamp);
}
Realize that Gson primarily is meant for Object Relational Mapping where you want to take that JSON and have it converted to a Java object. This is actually a lot simpler:
public class ResponseObject {
public String email;
public long timestamp;
public String event;
public String url;
public String userid;
public String template;
}
Because you have array of these, you want to use a TypeToken and Type to indicate your JSON is a List of these ResponseObject objects:
Type myListType = new TypeToken<List<ResponseObject>>(){}.getType();
List<ResponseObject> myList = new Gson().fromJson(jsonString, myListType);
{
"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);
}
I would like to create a JSON string as an array of objects like this:
[
{
"alertid": "1",
"alerttext": "This is test",
"alertdate": "2010-02-11 09:03:40"
},
{
"alertid": "2",
"alerttext": "Another alert",
"alertdate": "2010-02-11 09:11:04"
}
]
The JAVA JSON objects put method looks like this: jsonObject.put(String key, Collection value);
When I enter my key and collection, my json looks like this:
{
"JSONObject": [
{
"alertid": "1",
"alerttext": "This is test",
"alertdate": "2010-02-11 09:03:40"
},
{
"alertid": "2",
"alerttext": "Another alert",
"alertdate": "2010-02-11 09:11:04"
}
]
}
How can I get my json string to look like the first string when I am constrained to the signature of the put method?
If you're using the net.sf.json library, make yourself a JSONArray and put JSONObjects in it instead.
JSONArray array = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("alertid","1");
array.add(obj);
What you need is a JSONArray that you can then fill with JSONObject's
Try something like this:
JSONArray arr = new JSONArray();
for (JSONObject item : collection)
{
arr.put(item);
}
Or, if you already have a Collection of JSONObject's, you can simply write:
JSONArray arr = new JSONArray(yourFancyCollection);
Then, arr.toString() will look like you asked.