如何在Java中转换或转换哈希图到JSON对象,并再次将JSON对象转换为JSON字符串?


当前回答

你可以使用XStream——它真的很方便。请看这里的例子

package com.thoughtworks.xstream.json.test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

public class WriteTest {

    public static void main(String[] args) {

      HashMap<String,String> map = new HashMap<String,String>();
      map.add("1", "a");
      map.add("2", "b");
      XStream xstream = new XStream(new JettisonMappedXmlDriver());

      System.out.println(xstream.toXML(map));       

    }

}

其他回答

如果使用复杂对象,应该应用enableComplexMapKeySerialization(),如https://stackoverflow.com/a/24635655/2914140和https://stackoverflow.com/a/26374888/2914140中所述。

Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
Map<Point, String> original = new LinkedHashMap<Point, String>();
original.put(new Point(5, 6), "a");
original.put(new Point(8, 8), "b");
System.out.println(gson.toJson(original));

输出将是:

{
 "(5,6)": "a",
 "(8,8)": "b"
}

这对我来说很管用:

import groovy.json.JsonBuilder
properties = new Properties()
properties.put("name", "zhangsan")

println new JsonBuilder(properties).toPrettyString()

这个解决方案适用于复杂的json:

public Object toJSON(Object object) throws JSONException {
    if (object instanceof HashMap) {
        JSONObject json = new JSONObject();
        HashMap map = (HashMap) object;
        for (Object key : map.keySet()) {
            json.put(key.toString(), toJSON(map.get(key)));
        }
        return json;
    } else if (object instanceof Iterable) {
        JSONArray json = new JSONArray();
        for (Object value : ((Iterable) object)) {
            json.put(toJSON(value));
        }
        return json;
    }
    else {
        return object;
    }
}
    import org.json.JSONObject;

    HashMap<Object, Object> map = new HashMap<>();
    String[] list={"Grader","Participant"};
    String[] list1={"Assistant","intern"};
    map.put("TeachingAssistant",list);
    map.put("Writer",list1);
    JSONObject jsonObject = new JSONObject(map);
    System.out.printf(jsonObject.toString());

    // Result: {"TeachingAssistant":["Grader","Participant"],"Writer":["Assistant","intern"]}

你可以使用Gson。 这个库提供了将Java对象转换为JSON对象的简单方法,反之亦然。

例子:

GsonBuilder gb = new GsonBuilder();
Gson gson = gb.serializeNulls().create();
gson.toJson(object);

当需要设置默认选项以外的配置选项时,可以使用GsonBuilder。在上面的例子中,转换过程也将序列化object中的null属性。

但是,这种方法只适用于非泛型类型。对于泛型类型,你需要使用toJson(object, Type)。

更多关于Gson的信息请点击这里。

记住,对象必须实现Serializable接口。