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


当前回答

这个解决方案适用于复杂的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;
    }
}

其他回答

您可以使用Jackson将Map转换为JSON,如下所示:

Map<String,Object> map = new HashMap<>();
//You can convert any Object.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
map.put("key3","string1");
map.put("key4","string2");

String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);

Jackson的Maven依赖:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

If you are using `JSONObject` library, you can convert map to `JSON` as follows: JSONObject Library: import org.json.JSONObject; Map<String, Object> map = new HashMap<>(); // Convert a map having list of values. String[] value1 = new String[] { "value11", "value12", "value13" }; String[] value2 = new String[] { "value21", "value22", "value23" }; map.put("key1", value1); map.put("key2", value2); JSONObject json = new JSONObject(map); System.out.println(json); Maven Dependencies for `JSONObject` : <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20140107</version> </dependency> Hope this will help. Happy coding.

如果您正在使用JSR 374:用于JSON处理的Java API (javax JSON) 这似乎很管用:

    JsonObjectBuilder job = Json.createObjectBuilder((Map<String, Object>) obj);
    JsonObject jsonObject = job.build();

首先将所有对象转换为有效的string

HashMap<String, String> params = new HashMap<>();
params.put("arg1", "<b>some text</b>");
params.put("arg2", someObject.toString());

然后将整个映射插入到org.json.JSONObject中

JSONObject postData = new JSONObject(params);

现在您可以通过调用对象的toString来获取JSON

postData.toString()
//{"arg1":"<b>some text<\/b>" "arg2":"object output"}

创建一个新的JSONObject

JSONObject o = new JSONObject(postData.toString());

或者作为通过HTTP发送的字节数组

postData.toString().getBytes("UTF-8");

迟到的派对,但这里是我的GSON adhoc作家序列化hashmap。我必须写映射的键值对作为json字符串属性,期望一个特定的整数类型。我不想为这个简单的用例创建自定义JavaBean包装器。

GSON JsonWriter类是一个易于使用的序列化器类,它包含少量强类型writer.value()函数。

// write Map as JSON document to http servlet response
Map<String,String> sd = DAO.getSD(123);
res.setContentType("application/json; charset=UTF-8");
res.setCharacterEncoding("UTF-8");
JsonWriter writer = new JsonWriter(new OutputStreamWriter(res.getOutputStream(), "UTF-8"));
writer.beginObject();
for(String key : sd.keySet()) {
    String val = sd.get(key);
    writer.name(key);
    if (key.equals("UniqueID") && val!=null)
        writer.value(Long.parseLong(val));
    else
        writer.value(val);
}
writer.endObject();
writer.close();

如果不需要任何自定义类型,我可以只使用toJson()函数。jar库只有不到190KB,没有任何残酷的依赖关系。易于在任何自定义servlet应用程序或独立应用程序上使用,无需大型框架集成。

Gson gson = new Gson(); 
String json = gson.toJson(myMap); 
    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"]}