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


当前回答

在硒中反序列化自定义命令的响应时,我遇到了类似的问题。响应是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'负责类型删除警告。

其他回答

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

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

我使用阿里巴巴fastjson,简单明了:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>VERSION_CODE</version>
</dependency>

和导入:

import com.alibaba.fastjson.JSON;

然后:

String text = JSON.toJSONString(obj); // serialize
VO vo = JSON.parseObject("{...}", VO.class); //unserialize

一切都好。

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

你可以使用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"
}