1

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.

chani
  • 143
  • 1
  • 14
  • Have you already considered using Jackson-Mapper? - http://jackson.codehaus.org/ – pklndnst May 04 '15 at 13:13
  • @PatrickOutOfBounds, Can you give me example how to do that with Jackson-Mapper because I did not succeeded to do that. maybe your example will help me. – chani May 04 '15 at 13:15

5 Answers5

1

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"]}
Alok Mishra
  • 926
  • 13
  • 39
  • when I used this object I need to case the MyClass object to String befor putting it into the JSONObject object (using gson for exapmle) and then the output with be something like: {"sss":"{\"number\":1,\"s\":\"test\"}"} so it is not good for me... – chani May 04 '15 at 13:29
  • i have edited my answer , now its using Gson and you dont have to convert anything to string. @chani – Alok Mishra May 04 '15 at 13:50
0

Using Gson:

Gson gson = new GsonBuilder().create();
String json = gson.toJson(map);
Hussein Zawawi
  • 2,907
  • 2
  • 26
  • 44
  • I tried it but the json string output was: {"message":"java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType","code":1} – chani May 04 '15 at 13:21
0

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"}}
Abhishek
  • 6,912
  • 14
  • 59
  • 85
  • the (...) was just an example. I fixed the question. and you answer is the same of the previous answer. when I did it- I got this json string: {"message":"java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType","code":1} – chani May 04 '15 at 13:26
  • Please look into http://stackoverflow.com/questions/4226738/using-generics-with-gson – Abhishek May 04 '15 at 13:28
  • The link you gave me is how to deserialize and I am looking for way to serialize... – chani May 04 '15 at 13:50
  • Can you please share your code? We can look inito it and get back with solution – Abhishek May 04 '15 at 13:51
0

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));
    }
}
Parth Soni
  • 11,158
  • 4
  • 32
  • 54
  • this answer good for small class. but if my class have more then 15 members.... If I will not fine another way to do that. this is what I will do. but I hope to fine cleaner way... – chani May 04 '15 at 13:34
0

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

chani
  • 143
  • 1
  • 14