如何在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;
    }
}

其他回答

你可以使用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));       

    }

}

在硒中反序列化自定义命令的响应时,我遇到了类似的问题。响应是json,但selenium在内部将其转换为java.util。HashMap(字符串、对象)

如果你熟悉scala并使用play-API来处理JSON,你可能会从中受益:

import play.api.libs.json.{JsValue, Json}
import scala.collection.JavaConversions.mapAsScalaMap


object JsonParser {

  def parse(map: Map[String, Any]): JsValue = {
    val values = for((key, value) <- map) yield {
      value match {
        case m: java.util.Map[String, _] @unchecked => Json.obj(key -> parse(m.toMap))
        case m: Map[String, _] @unchecked => Json.obj(key -> parse(m))
        case int: Int => Json.obj(key -> int)
        case str: String => Json.obj(key -> str)
        case bool: Boolean => Json.obj(key -> bool)
      }
    }

    values.foldLeft(Json.obj())((temp, obj) => {
      temp.deepMerge(obj)
    })
  }
}

小代码说明:

代码递归遍历HashMap,直到找到基本类型(String、Integer、Boolean)。这些基本类型可以直接包装到JsObject中。展开递归时,deepmerge将连接创建的对象。

'@unchecked'负责类型删除警告。

首先将所有对象转换为有效的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");

您只需枚举映射并将键-值对添加到JSONObject

方法:

private JSONObject getJsonFromMap(Map<String, Object> map) throws JSONException {
    JSONObject jsonData = new JSONObject();
    for (String key : map.keySet()) {
        Object value = map.get(key);
        if (value instanceof Map<?, ?>) {
            value = getJsonFromMap((Map<String, Object>) value);
        }
        jsonData.put(key, value);
    }
    return jsonData;
}

如果使用复杂对象,应该应用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"
}