如何在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接口。
推荐文章
- 在流中使用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