如何在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");
其他回答
您只需枚举映射并将键-值对添加到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;
}
你可以使用Gson。 这个库提供了将Java对象转换为JSON对象的简单方法,反之亦然。
例子:
GsonBuilder gb = new GsonBuilder();
Gson gson = gb.serializeNulls().create();
gson.toJson(object);
当需要设置默认选项以外的配置选项时,可以使用GsonBuilder。在上面的例子中,转换过程也将序列化object中的null属性。
但是,这种方法只适用于非泛型类型。对于泛型类型,你需要使用toJson(object, Type)。
更多关于Gson的信息请点击这里。
记住,对象必须实现Serializable接口。
这对我来说很管用:
import groovy.json.JsonBuilder
properties = new Properties()
properties.put("name", "zhangsan")
println new JsonBuilder(properties).toPrettyString()
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"]}
如果使用复杂对象,应该应用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"
}
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 查询JSON类型内的数组元素
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder