找到你要的答案

Q:How to convert Map of class objects to json java

Q:如何将地图类对象以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.

我有一些属性的类,例如:

public class MyClass {
    public int number;
    public String s;
}

我想把地图这类JSON。例如:

Map<String, MyClass> map = new HashMap();
map.put("sss", new MyClass(1, "blabla");

json j = new json(map);

我希望输出像:

{"sss":{"number":"1","s":"blabla"}}

有人知道如何在java做的?我试着与JSONObject和Gson却没有为我工作。

answer1: 回答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"]}

你可以使用gson类tojson()方法将一个java对象的JSON,见下面的例子,

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 + "]";
    }

}

我将把上述类的对象以JSON的getter和setter方法是有用的当你转换JSON回java对象。

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);

        }

输出:

{"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]}
answer2: 回答2:

Using Gson:

Gson gson = new GsonBuilder().create();
String json = gson.toJson(map);

使用Gson:

Gson gson = new GsonBuilder().create();
String json = gson.toJson(map);
answer3: 回答3:

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"}}

你要解决的问题,括号。

map.put("sss", new MyClass(1,"test")); //observe 2 braces at the end!

下面的代码应该为你做窍门,

Gson gson = new Gson();
String myJson = gson.toJson(map);

输出:

{"sss":{"number":1,"s":"test"}}
answer4: 回答4:

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));
    }
}

实现一些自定义tojson()方法为每个类如下图所示:

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+"\"}");
    }

}

然后就用它来转换你的地图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));
    }
}
answer5: 回答5:

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

我找到了怎么做的方法:

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();

现在输出是正确的。

非常感谢所有试图帮助我解决这个问题的人…

answer6: 回答6:

To complement my comment: Using Jackson an example could look like this:

public class MyClass {

    @JsonSerialize
    public int number;

    @JsonSerialize
    public String s;

    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, MyClass> map = new HashMap();
            map.put("sss", new MyClass(1, "blabla");
            System.out.println(objectMapper.writeValueAsString(map));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

补充我的评论:使用杰克逊的例子可以像这样:

public class MyClass {

    @JsonSerialize
    public int number;

    @JsonSerialize
    public String s;

    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, MyClass> map = new HashMap();
            map.put("sss", new MyClass(1, "blabla");
            System.out.println(objectMapper.writeValueAsString(map));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}
java  json  gson