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


当前回答

这通常是Json库的工作,你不应该尝试自己做。所有json库都应该实现您所要求的内容,而且您可以做到 在页面底部的json.org上找到Java 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));       

    }

}

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

我使用阿里巴巴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

一切都好。

对于使用org.json.simple的用户。JSONObject,你可以将映射转换为Json String并解析它来获得JSONObject。

JSONObject object = (JSONObject) new JSONParser().parse(JSONObject.toJSONString(map));

对于使用TypeToken的更复杂的映射和列表,Gson是一种方式。getParameterized方法:

我们有一张这样的地图:

Map<Long, List<NewFile>> map;

我们使用上面提到的getParameterized方法来获取类型,如下所示:

Type listOfNewFiles = TypeToken.getParameterized(ArrayList.class, NewFile.class).getType();
Type mapOfList = TypeToken.getParameterized(LinkedHashMap.class, Long.class, listOfNewFiles).getType();

然后使用Gson对象fromJson方法,使用mapflist对象,像这样:

Map<Long, List<NewFile>> map = new Gson().fromJson(fileContent, mapOfList);

上面提到的对象NewFile看起来是这样的:

class NewFile
{
    private long id;
    private String fileName;

    public void setId(final long id)
    {
        this.id = id;
    }

    public void setFileName(final String fileName)
    {
        this.fileName = fileName;
    }
}

反序列化的JSON是这样的:

{ “1”:[ { “id”:12232年, “文件名”:“test.html” }, { “id”:12233年, “文件名”:“file.txt” }, { “id”:12234年, “文件名”:“obj.json” } ], “2”:[ { “id”:122321年, “文件名”:“test2.html” }, { “id”:122332年, “文件名”:“file2.txt” }, { “id”:122343年, “文件名”:“obj2.json” } ] }