How to generate Json with Java - 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.

Related

How to write custom serializer for proxy classes

I need to serialize/deserialize a POJO with enum. I have the following DTO:
public enum MyEnum {
VAL1("val1"),
VAL2("val2") {
#Override
public String getValue() {
return "test2";
}
};
private final String name;
MyEnum(String name) {
this.name = name;
}
public String getValue() {
return name;
}
}
public class MyPojo {
public MyEnum prop;
}
public static void main(String... args) {
Gson gson = new GsonBuilder().registerTypeAdapter(MyEnum.class, new MyEnumSeserializer());
MyPojo p = new MyPojo();
p.prop = MyEnum.VAL2; // and I get MyEnum$1.class and My serializer doesn't work
String json = gson.toJson(p);
MyPojo p1 = gson.fromJson(json, MyPojo.class);
}
How can I write a custom serializer/deserializer for proxy classes using Gson library? I can't use another library.
I've been found the solution. Need to change
new GsonBuilder().registerTypeAdapter(MyEnum.class, new MyEnumSeserializer());
to
new GsonBuilder(). registerTypeHierarchyAdapter(MyEnum.class, new MyEnumSeserializer());
and all work fine.

Gson- Parsing a JSON array of JSON objects to ArrayList<org.json.JSONObject>

I have a JSON string like this:
{
"r": [
{
"pic": "1.jpg",
"name": "Name1"
},
{
"pic": "2.jpg",
"name": "Name2"
},
{
"pic": "3.jpg",
"name": "Name3"
}
]
}
I want to parse to this POJO model:
public class Catalog {
#SerializedName("r")
#Expose
private List<JSONObject> r = new ArrayList<JSONObject>();
public List<JSONObject> getR() {
return r;
}
public void setR(List<JSONObject> r) {
this.r = r;
}
}
I am parsing this way:
Catalog cat = new Gson().fromJson(jsonString,Catalog.class);
But finally am getting this json
{
"r": [
{
"nameValuePairs": {}
},
{
"nameValuePairs": {}
},
{
"nameValuePairs": {}
}
]
}
Please note that I don't want to use com.google.gson.JsonObject.
I want to use org.json.JSONObject. How to achieve this because almost all of my code uses it?
As it was already mentioned in other answer and comments, you probably might not really want to use org.json.JSONObject for several reasons. But if it's a must for you, you just have to create your org.json.JSONObject-aware Gson instance.
final class JSONObjectJsonDeserializer
implements JsonDeserializer<JSONObject> {
// The implementation is fully thread-safe and can be instantiated once
private static final JsonDeserializer<JSONObject> jsonObjectJsonDeserializer = new JSONObjectJsonDeserializer();
// Type tokens are immutable values and therefore can be considered constants (and final) and thread-safe as well
private static final TypeToken<Map<String, Object>> mapStringToObjectTypeToken = new TypeToken<Map<String, Object>>() {
};
private JSONObjectJsonDeserializer() {
}
static JsonDeserializer<JSONObject> getJsonObjectJsonDeserializer() {
return jsonObjectJsonDeserializer;
}
#Override
public JSONObject deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) {
// Convert the input jsonElement as if it were a Map<String, Object> (a generic representation for JSON objectS)
final Map<String, Object> map = context.deserialize(jsonElement, mapStringToObjectTypeToken.getType());
// And forward the map to the JSONObject constructor - it seems to accept it nice
return new JSONObject(map);
}
}
Gson is designed thread-safe and does not need to be instantiated every time serialization or deserialization is necessary:
private static final Gson gson = new GsonBuilder()
.registerTypeAdapter(JSONObject.class, getJsonObjectJsonDeserializer())
.create();
And finally:
final Catalog catalog = gson.fromJson(jsonString, Catalog.class);
out.println(catalog.getR());
with the following result:
[{"name":"Name1","pic":"1.jpg"}, {"name":"Name2","pic":"2.jpg"}, {"name":"Name3","pic":"3.jpg"}]
Anyway, I would suggest you to redesign your mappings model.
I think you don't need JSONObject.
Try this
// is wrapped class for serialized json.
public class JsonExample
{
List<Catalog> r;
}
public class Catalog {
private String pic;
private String name;
public String getPic() {
return pic;
}
public String getName() {
return name;
}
}
JsonExample example = new Gson().fromJson(json, JsonExample.class);
Additional - using JSONObject
JSONObject obj = new JSONObject(json);
JSONArray arr = obj.getJSONArray("r");
List<Catalog> cataList = new ArrayList<>();
for(int i = 0 ; i < arr.length() ; ++i)
{
cataList.add(new Catalog(arr.getJSONObject(i)));
}
public class Catalog {
private String pic;
private String name;
public Catalog(JSONObject obj) throws JSONException
{
pic = obj.getString("pic");
name = obj.getString("name");
}
public String getPic() {
return pic;
}
public String getName() {
return name;
}
}
I think in your case, usage of gson library is not required at all.
Only org.json can solve the entire problem.
E.g.:
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONArray("r");
List<JSONObject> jsonList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}
Catalog catalog = new Catalog();
catalog.setR(jsonList);

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 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...

JSON parsing only one branch of whole message java using GsonBuilder and InputStream Android

I just try to integrate with external webservice via JSON from Android. I receive following JSON format:
Data that i'm interested in is in "messages" branch.
To access data i'm using :
builder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
Gson gson = builder.create();
ClassToStore response = gson.fromJson(reader, ClassToStore.class);
where reader is a input stream from:
am = getInstrumentation().getContext().getAssets();
am.open("data.json");
Message structure looks like:
ClassToStore has all fields with the same names.
I get all objects but all of theme are null's
PLEASE HELP :(
My classToStore:
public static class ClassToStore implements Serializable {
private static final long serialVersionUID = -1463052486583654136L;
public String id ;
public String replied_to_id ;
public String sender_id ;
public String created_at ;
public String getId() {
return id;
}
public String getReplied_to_id() {
return replied_to_id;
}
public String getSender_id() {
return sender_id;
}
public String getCreated_at() {
return created_at;
}
}
You will need an extra class to match the outer object:
public class OuterObject {
List<ClassToStore> messages;
}
And then load it like this:
Gson gson = new Gson();
Type type = new TypeToken<List<OuterObject>>(){}.getType();
List<OuterObject> outerList = gson.fromJson(reader, type);
List<ClassToStore> listOfMessages = outerlist.get(0).messages;

Categories

Resources