gson - include class name when serializing java pojo -> json - java

Using GSON how do I append the class name of my List to my outputted json string? I've looked through the api and have missed any reference to do this. I'm using GsonBuilder in my real code but don't see any options for it either.
public class Person {
String name;
public Person(String name){
this.name = name;
}
public static void main(String [] args){
Person one = new Person("Alice");
Person two = new Person("Bob");
List<Person> people = new ArrayList<Person>();
people.add(one);
people.add(two);
String json = new Gson(people);
}
}
This gives the following output:
json = [{"name": "Alice"},{"name": "Bob"}]
How do I achieve the following output? or something similar.
json = {"person":[{"name": "Alice"},{"name": "Bob"}]}
or
json = [{"person":{"name": "Alice"}},{"person":{"name": "Bob"}}]
Hope it's something trivial that I have just missed. Thanks in advance.

I don't know if the answer is still interesting you but what you can do is the following:
public static void main(String [] args){
Person one = new Person("Alice");
Person two = new Person("Bob");
List<Person> people = new ArrayList<Person>();
people.add(one);
people.add(two);
Gson gson = new Gson();
JsonElement je = gson.toJsonTree(people);
JsonObject jo = new JsonObject();
jo.add("person", je);
System.out.println(jo.toString()); //prints {"person":[{"name": "Alice"},{"name": "Bob"}]}
}

Related

GSON does not return JSON key

I am using GSON to convert objects into JSON. I have this:
String name = "MyName";
and I use the following statement to convert it to json:
print(new Gson().toJson(name));
and the output is : "MyName"
How can I make it print in this way:
{"name":"myName"}
There are two options:
class YourClass {
private String name;
// getters and setters...
}
YourClass object = new YourClass();
object.setName("MyName");
print(new Gson().toJson(object));
And using JsonObject:
JsonObject object = new JsonObject();
object.addProperty("name", "MyName");
print(new Gson().toJson(object);
public class Test {
String name = "myName";
public static void main(String[] args) {
System.out.println(new Gson().toJson(new Test()));
}
}

How to generate Json with Java

I am working on an application where i have to generate a json like this:
[
{"title":"Culture","start":"Salary","end":"Work"},
{"title":"Work","start":"Salary","end":"Work"}
]
But my code generates json like this:
{{"name":"Culture"},[{"name":"Salary"},{"name":"Work"}],}
My code:
public class ParseJson {
public static class EntryListContainer {
public List<Entry> children = new ArrayList<Entry>();
public Entry name;
}
public static class Entry {
private String name;
public Entry(String name) {
this.name = name;
}
}
public static void main(String[] args) {
EntryListContainer elc1 = new EntryListContainer();
elc1.name = new Entry("Culture");
elc1.children.add(new Entry("Salary"));
elc1.children.add(new Entry("Work"));
ArrayList<EntryListContainer> al = new ArrayList<EntryListContainer>();
Gson g = new Gson();
al.add(elc1);
StringBuilder sb = new StringBuilder("{");
for (EntryListContainer elc : al) {
sb.append(g.toJson(elc.name));
sb.append(",");
sb.append(g.toJson(elc.children));
sb.append(",");
}
String partialJson = sb.toString();
if (al.size() > 1) {
int c = partialJson.lastIndexOf(",");
partialJson = partialJson.substring(0, c);
}
String finalJson = partialJson + "}";
System.out.println(finalJson);
}
}
Can anyone help me to generate this json in my required format ?? please thanks in advance
Try this
public class Entry {
public String title;
public String start;
public String end;
}
And in another part of your code
private ArrayList<Entry> entries = new ArrayList<>();
// Fill the entries...
String the_json = new Gson().toJson(entries);
1) First Create your POJO
public class MyJSONObject {
private String title;
private String start;
private String end;
//getter and setter methods
[...]
#Override
public String toString() {
}
}
2) Use com.google.code.gson library
public static void main(String[] args) {
{
ArrayList<MyJSONObject> myJSONArray = new ArrayList<>();
MyJSONObject obj = new MyJSONObject();
obj.setTitle="Culture";
obj.set[...]
myJSONArray.add(obj);
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(myJSONArray);
System.out.println(json);
}
Output : [{"title":"Culture","start":"Salary","end":"Work"}, ...]
I recommend you to use some JSON Java API, like Gson. It's very simple to generate a string json from a POJO object or to create a POJO object from a string json.
The code for generating a string json from a POJO object is like this:
Gson gson = new Gson();
String stringJson = gson.toJson(somePojoObject);
The code for creating a POJO object from a string json is like this:
Gson gson = new Gson();
SomePojoClass object = gson.fromJson(stringJson, SomePojoClass.class);
Note that you can not serialize objects with circular references. This causes infinite recursion.

How to convert Map of class<T> objects to json java

I have class with some properties, for example:
public class MyClass {
public int number;
public String s;
}
and I want to convert Map of this class to json. for example:
Map<String, MyClass> map = new HashMap();
map.put("sss", new MyClass(1, "blabla");
json j = new json(map);
and I want the output to be like:
{"sss":{"number":"1","s":"blabla"}}
someone know how to do that in JAVA? I tried with JSONObject and with Gson but did not work for me.
you can use toJson() method of Gson class to convert a java object to json ,see the example below ,
public class SomeObject {
private int data1 = 100;
private String data2 = "hello";
private List<String> list = new ArrayList<String>() {
{
add("String 1");
add("String 2");
add("String 3");
}
};
//getter and setter methods
#Override
public String toString() {
return "SomeObject [data1=" + data1 + ", data2=" + data2 + ", list="
+ list + "]";
}
}
i will convert the above class' object to json , getter and setter methods are useful when you are converting the json back to java object .
public static void main(String[] args) {
SomeObject obj = new SomeObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
System.out.println(json);
}
output :
{"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]}
Using Gson:
Gson gson = new GsonBuilder().create();
String json = gson.toJson(map);
You have to fix, parenthesis issue.
map.put("sss", new MyClass(1,"test")); //observe 2 braces at the end!
Following code should do the trick for you,
Gson gson = new Gson();
String myJson = gson.toJson(map);
Output:
{"sss":{"number":1,"s":"test"}}
Implement some custom toJSON() method for each class as shown below:
public class MyClass1 {
String number;
String name;
public MyClass1(String number, String name){
this.number = number;
this.name = name;
}
public JSONObject toJSON() throws JSONException {
return new JSONObject("{\"number\" : \""+this.number+"\", \"name\":\""+this.name+"\"}");
}
}
And then just use it to convert your map to jsonObject:
public class MapToJSON {
public static void main(String[] args) throws JSONException {
Map<String, JSONObject> map = new HashMap<String, JSONObject>();
map.put("sss", new MyClass1("1", "Hello").toJSON());
System.out.println(new JSONObject(map));
}
}
I found the way how to do that:
import com.google.gson.Gson;
import org.json.JSONObject;
Gson gson = new Gson();
map.put("sss", new JSONObject(gson.toJson(new MyClass(1, "Hello"))));
map.put("aaa", new JSONObject(gson.toJson(new MyClass(2, "blabla"))));
String output = new JSONObject(map).toString();
and now the output is correct.
Thanks a lot to all the people that tried to help me with this problem...

use GSON in jsp page

I'm trying to serialize an object in JSON using a JSP like format using the following code:
ArrayList<AccountBean> al = new ArrayList<AccountBean>();
al = vc.getAccountName();
int i=0;
out.print("[");
while(i<al.size()){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
out.print("{ID"+al.get(i).getAno()+":name"+al.get(i).getAccount_name()+"},");
i++;
}
out.print("]");
I'm getting a output like this:
[{ID1:nameEquity Share Capitals},{ID2:nameCalls In Arear},]
but my requirement is something like this:
[{"ID1":"nameEquity Share Capitals"},{"ID2":"nameCalls In Arear"}]
out.print('{"ID'+al.get(i).getAno()+'":"name'+al.get(i).getAccount_name()+'"},')
use ' to open/close the string, and " to wrap your json keys/values.
Otherwise you can do like this
out.print("{\"ID"+al.get(i).getAno()+"\":\"name"+al.get(i).getAccount_name()+"\"},")
escaping the quotes with \"
Anyway, have you tried this?
String json = gson.toJson(al)
Have a look here for more info: https://sites.google.com/site/gson/gson-user-guide
Best way to do this is using a custom serializer and I can edit this answer posting one if you want to go deeper.
However, since you are quite new to JSON and Gson I would answer with this simple code that you can paste&try in you IDE. I just "convert" you bean into a map, and the use Gson to serialize.
package stackoverflow.questions;
import java.util.*;
import com.google.gson.Gson;
public class Q20323412 {
public static class AccountBean{
Integer _id;
String _name;
public String getAccount_name(){
return _name;
}
public Integer getAno(){
// what a weird name, in italian for this method..
return _id;
}
public AccountBean(Integer id, String name){
_id = id;
_name = name;
}
}
/**
* #param args
*/
public static void main(String[] args) {
ArrayList<AccountBean> al = new ArrayList<AccountBean>();
al.add(new AccountBean(1, "Equity Share Capitals"));
al.add(new AccountBean(2, "Calls In Arear"));
ArrayList<Map> al2 = new ArrayList<>();
for(AccountBean account : al){
HashMap hm = new HashMap();
hm.put("ID"+ account.getAno(), "name"+account.getAccount_name());
al2.add(hm);
}
Gson g = new Gson();
System.out.println(g.toJson(al2));
}
}
Since you did not post your bean, I invented one that has features similar to your's.

Gson custom deserialization

I'm using Gson to create and parse JSON, but I've faced one problem. In my code I use this field:
#Expose
private ArrayList<Person> persons = new ArrayList<Person>();
But my JSON is formated like this:
persons:{count:"n", data:[...]}
Data is an array of persons.
Is there any way to convert this JSON into my class using Gson? Can I use a JsonDeserializer?
You'll need a custom deserializer (http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonDeserializer.html), something like:
public static class MyJsonAdapter implements JsonDeserializer<List<Person>>
{
List<Person> people = new ArrayList<>();
public List<Person> deserialize( JsonElement jsonElement, Type type, JsonDeserializationContext context )
throws JsonParseException
{
for (each element in the json data array)
{
Person p = context.deserialize(jsonElementFromArray,Person.class );
people.add(p);
}
}
return people;
}
You can try below code to parse your json
String jsonInputStr = "{count:"n", data:[...]}";
Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson(jsonInputStr, JsonElement.class).getAsJsonObject();
List<Person> persons = gson.fromJson(jsonObj.get("data").toString(), new TypeToken<List<Person>>(){}.getType());

Categories

Resources