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


当前回答

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

其他回答

如果你真的不需要HashMap,你可以这样做:

String jsonString = new JSONObject() {{
  put("firstName", user.firstName);
  put("lastName", user.lastName);
}}.toString();

输出:

{
  "firstName": "John",
  "lastName": "Doe"
}

以下是我与GSON的单线解决方案:

myObject = new Gson().fromJson(new Gson().toJson(myHashMap), MyClass.class);

java库可以将哈希映射或数组列表转换为json,反之亦然。

import com.github.underscore.U;
import java.util.*;

public class Main {

    public static void main(String[] args) {

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("1", "a");
        map.put("2", "b");

        System.out.println(U.toJson(map));
        // {
        //    "1": "a",
        //    "2": "b"
        // }
    }
}

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

    }

}

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

例子:

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

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

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

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

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