如何在Java中转换或转换哈希图到JSON对象,并再次将JSON对象转换为JSON字符串?
这通常是Json库的工作,你不应该尝试自己做。所有json库都应该实现您所要求的内容,而且您可以做到 在页面底部的json.org上找到Java Json库的列表。
你可以使用:
new JSONObject(map);
其他函数可以从它的文档中获得 http://stleary.github.io/JSON-java/index.html
使用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/
你可以使用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还可以用于序列化任意复杂的对象。
下面是如何使用它:
Gson gson = new Gson();
String json = gson.toJson(myObject);
Gson将自动将集合转换为JSON数组。Gson可以序列化私有字段并自动忽略瞬态字段。
迟到的派对,但这里是我的GSON adhoc作家序列化hashmap。我必须写映射的键值对作为json字符串属性,期望一个特定的整数类型。我不想为这个简单的用例创建自定义JavaBean包装器。
GSON JsonWriter类是一个易于使用的序列化器类,它包含少量强类型writer.value()函数。
// write Map as JSON document to http servlet response
Map<String,String> sd = DAO.getSD(123);
res.setContentType("application/json; charset=UTF-8");
res.setCharacterEncoding("UTF-8");
JsonWriter writer = new JsonWriter(new OutputStreamWriter(res.getOutputStream(), "UTF-8"));
writer.beginObject();
for(String key : sd.keySet()) {
String val = sd.get(key);
writer.name(key);
if (key.equals("UniqueID") && val!=null)
writer.value(Long.parseLong(val));
else
writer.value(val);
}
writer.endObject();
writer.close();
如果不需要任何自定义类型,我可以只使用toJson()函数。jar库只有不到190KB,没有任何残酷的依赖关系。易于在任何自定义servlet应用程序或独立应用程序上使用,无需大型框架集成。
Gson gson = new Gson();
String json = gson.toJson(myMap);
如果你正在使用net.sf.json.JSONObject,那么你不会在其中找到JSONObject(map)构造函数。您必须使用公共静态JSONObject fromObject(对象对象)方法。该方法接受JSON格式的字符串、map、dynabean和javabean。
JSONObject jsonObject = JSONObject.fromObject(myMap);
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"
// }
}
}
如果你需要在代码中使用它。
Gson gsone = new Gson();
JsonObject res = gsone.toJsonTree(sqlParams).getAsJsonObject();
就我而言,我不想要任何依赖。使用Java 8,你可以得到一个JSON字符串,如下所示:
Map<String, Object> map = new HashMap<>();
map.put("key", "value");
map.put("key2", "value2");
String json = "{"+map.entrySet().stream()
.map(e -> "\""+ e.getKey() + "\":\"" + String.valueOf(e.getValue()) + "\"")
.collect(Collectors.joining(", "))+"}";
在硒中反序列化自定义命令的响应时,我遇到了类似的问题。响应是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'负责类型删除警告。
你可以使用Gson。 这个库提供了将Java对象转换为JSON对象的简单方法,反之亦然。
例子:
GsonBuilder gb = new GsonBuilder();
Gson gson = gb.serializeNulls().create();
gson.toJson(object);
当需要设置默认选项以外的配置选项时,可以使用GsonBuilder。在上面的例子中,转换过程也将序列化object中的null属性。
但是,这种方法只适用于非泛型类型。对于泛型类型,你需要使用toJson(object, Type)。
更多关于Gson的信息请点击这里。
记住,对象必须实现Serializable接口。
如果使用复杂对象,应该应用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"
}
您只需枚举映射并将键-值对添加到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;
}
您可以使用Jackson将Map转换为JSON,如下所示:
Map<String,Object> map = new HashMap<>();
//You can convert any Object.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
map.put("key3","string1");
map.put("key4","string2");
String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);
Jackson的Maven依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
If you are using `JSONObject` library, you can convert map to `JSON` as follows: JSONObject Library: import org.json.JSONObject; Map<String, Object> map = new HashMap<>(); // Convert a map having list of values. String[] value1 = new String[] { "value11", "value12", "value13" }; String[] value2 = new String[] { "value21", "value22", "value23" }; map.put("key1", value1); map.put("key2", value2); JSONObject json = new JSONObject(map); System.out.println(json); Maven Dependencies for `JSONObject` : <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20140107</version> </dependency> Hope this will help. Happy coding.
以下是我与GSON的单线解决方案:
myObject = new Gson().fromJson(new Gson().toJson(myHashMap), MyClass.class);
不需要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));
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"]}
我找到了另一种处理方法。
Map obj=new HashMap();
obj.put("name","sonoo");
obj.put("age",new Integer(27));
obj.put("salary",new Double(600000));
String jsonText = JSONValue.toJSONString(obj);
System.out.print(jsonText);
希望这能有所帮助。
谢谢。
如果你真的不需要HashMap,你可以这样做:
String jsonString = new JSONObject() {{
put("firstName", user.firstName);
put("lastName", user.lastName);
}}.toString();
输出:
{
"firstName": "John",
"lastName": "Doe"
}
这对我来说很管用:
import groovy.json.JsonBuilder
properties = new Properties()
properties.put("name", "zhangsan")
println new JsonBuilder(properties).toPrettyString()
我使用阿里巴巴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
一切都好。
这个解决方案适用于复杂的json:
public Object toJSON(Object object) throws JSONException {
if (object instanceof HashMap) {
JSONObject json = new JSONObject();
HashMap map = (HashMap) object;
for (Object key : map.keySet()) {
json.put(key.toString(), toJSON(map.get(key)));
}
return json;
} else if (object instanceof Iterable) {
JSONArray json = new JSONArray();
for (Object value : ((Iterable) object)) {
json.put(toJSON(value));
}
return json;
}
else {
return object;
}
}
迟到总比不到好。如果你想要一个序列化的列表,我使用GSON将HashMap列表转换为字符串。
List<HashMap<String, String>> list = new ArrayList<>();
HashMap<String,String> hashMap = new HashMap<>();
hashMap.add("key", "value");
hashMap.add("key", "value");
hashMap.add("key", "value");
list.add(hashMap);
String json = new Gson().toJson(list);
这个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");
如果您正在使用JSR 374:用于JSON处理的Java API (javax JSON) 这似乎很管用:
JsonObjectBuilder job = Json.createObjectBuilder((Map<String, Object>) obj);
JsonObject jsonObject = job.build();
我们使用Gson。
Gson gson = new Gson();
Type gsonType = new TypeToken<HashMap>(){}.getType();
String gsonString = gson.toJson(elements,gsonType);
对于使用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” } ] }
推荐文章
- 在流中使用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