如何在Java中转换或转换哈希图到JSON对象,并再次将JSON对象转换为JSON字符串?
当前回答
不需要Gson或JSON解析库。 只需使用新的JSONObject(Map<String, JSONObject>).toString(),例如:
/**
* convert target map to JSON string
*
* @param map the target map
* @return JSON string of the map
*/
@NonNull public String toJson(@NonNull Map<String, Target> map) {
final Map<String, JSONObject> flatMap = new HashMap<>();
for (String key : map.keySet()) {
try {
flatMap.put(key, toJsonObject(map.get(key)));
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
// 2 indentSpaces for pretty printing
return new JSONObject(flatMap).toString(2);
} catch (JSONException e) {
e.printStackTrace();
return "{}";
}
}
其他回答
对于使用org.json.simple的用户。JSONObject,你可以将映射转换为Json String并解析它来获得JSONObject。
JSONObject object = (JSONObject) new JSONParser().parse(JSONObject.toJSONString(map));
使用json的示例
Map<String, Object> data = new HashMap<String, Object>();
data.put( "name", "Mars" );
data.put( "age", 32 );
data.put( "city", "NY" );
JSONObject json = new JSONObject();
json.putAll( data );
System.out.printf( "JSON: %s", json.toString(2) );
输出:
JSON: {
"age": 32,
"name": "Mars",
"city": "NY"
}
你也可以尝试使用谷歌的GSON。谷歌的GSON是将Java对象转换为JSON表示形式的最佳库。
http://code.google.com/p/google-gson/
如果您正在使用JSR 374:用于JSON处理的Java API (javax JSON) 这似乎很管用:
JsonObjectBuilder job = Json.createObjectBuilder((Map<String, Object>) obj);
JsonObject jsonObject = job.build();
你可以使用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或JSON解析库。 只需使用新的JSONObject(Map<String, JSONObject>).toString(),例如:
/**
* convert target map to JSON string
*
* @param map the target map
* @return JSON string of the map
*/
@NonNull public String toJson(@NonNull Map<String, Target> map) {
final Map<String, JSONObject> flatMap = new HashMap<>();
for (String key : map.keySet()) {
try {
flatMap.put(key, toJsonObject(map.get(key)));
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
// 2 indentSpaces for pretty printing
return new JSONObject(flatMap).toString(2);
} catch (JSONException e) {
e.printStackTrace();
return "{}";
}
}
推荐文章
- 在流中使用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