Java 将 JSON 转换为地图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/443499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert JSON to Map
提问by David Santamaria
What is the best way to convert a JSON code as this:
将 JSON 代码转换为这样的最佳方法是什么:
{
"data" :
{
"field1" : "value1",
"field2" : "value2"
}
}
in a Java Map in which one the keys are (field1, field2) and the values for those fields are (value1, value2).
在 Java Map 中,其中一个键是 (field1, field2),这些字段的值是 (value1, value2)。
Any ideas? Should I use Json-lib for that? Or better if I write my own parser?
有任何想法吗?我应该为此使用 Json-lib 吗?或者如果我编写自己的解析器更好?
采纳答案by StaxMan
I hope you were joking about writing your own parser. :-)
我希望你是在开玩笑写你自己的解析器。:-)
For such a simple mapping, most tools from http://json.org(section java) would work. For one of them (Hymanson, http://wiki.fasterxml.com/HymansonInFiveMinutes), you'd do:
对于这样一个简单的映射,来自http://json.org(java 部分)的大多数工具都可以使用。对于其中之一(Hyman逊,http://wiki.fasterxml.com/HymansonInFiveMinutes),你会这样做:
HashMap<String,Object> result =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
(where JSON_SOURCE is a File, input stream, reader, or json content String)
(其中 JSON_SOURCE 是文件、输入流、读取器或 json 内容字符串)
回答by Bruno Ranschaert
回答by StaxMan
JSON to Map always gonna be a string/object data type. i haved GSON lib from google.
JSON to Map 始终是字符串/对象数据类型。我从谷歌获得了 GSON 库。
works very well and JDK 1.5 is the min requirement.
效果很好,最低要求是 JDK 1.5。
回答by j.d.
Use JSON lib E.g. http://www.json.org/java/
使用 JSON lib 例如http://www.json.org/java/
// Assume you have a Map<String, String> in JSONObject jdata
@SuppressWarnings("unchecked")
Iterator<String> nameItr = jdata.keys();
Map<String, String> outMap = new HashMap<String, String>();
while(nameItr.hasNext()) {
String name = nameItr.next();
outMap.put(name, jdata.getString(name));
}
回答by David L
Using the GSON library:
使用 GSON 库:
import com.google.gson.Gson;
import com.google.common.reflect.TypeToken;
import java.lang.reclect.Type;
Use the following code:
使用以下代码:
Type mapType = new TypeToken<Map<String, Map>>(){}.getType();
Map<String, String[]> son = new Gson().fromJson(easyString, mapType);
回答by bugs_
I like google gsonlibrary.
When you don't know structure of json. You can use
我喜欢谷歌 gson库。
当你不知道 json 的结构时。您可以使用
JsonElement root = new JsonParser().parse(jsonString);
and then you can work with json. e.g. how to get "value1" from your gson:
然后你可以使用json。例如,如何从您的 gson 中获取“value1”:
String value1 = root.getAsJsonObject().get("data").getAsJsonObject().get("field1").getAsString();
回答by Fabio Araujo
This way its works like a Map...
这样它就像地图一样工作......
JSONObject fieldsJson = new JSONObject(json);
String value = fieldsJson.getString(key);
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.1</version>
</dependency>
回答by newMaziar
java.lang.reflect.Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Gson gson = new Gson();
Map<String, Object> categoryicons = gson.fromJson(json, mapType );
回答by Jad B.
My post could be helpful for others, so imagine you have a map with a specific object in values, something like that:
我的帖子可能对其他人有帮助,因此想象一下您有一张地图,其中包含特定对象的值,如下所示:
{
"shopping_list":{
"996386":{
"id":996386,
"label":"My 1st shopping list",
"current":true,
"nb_reference":6
},
"888540":{
"id":888540,
"label":"My 2nd shopping list",
"current":false,
"nb_reference":2
}
}
}
To parse this JSON file with GSON library, it's easy : if your project is mavenized
要使用 GSON 库解析这个 JSON 文件,很简单:如果您的项目是 mavenized
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
Then use this snippet :
然后使用这个片段:
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
//Read the JSON file
JsonElement root = new JsonParser().parse(new FileReader("/path/to/the/json/file/in/your/file/system.json"));
//Get the content of the first map
JsonObject object = root.getAsJsonObject().get("shopping_list").getAsJsonObject();
//Iterate over this map
Gson gson = new Gson();
for (Entry<String, JsonElement> entry : object.entrySet()) {
ShoppingList shoppingList = gson.fromJson(entry.getValue(), ShoppingList.class);
System.out.println(shoppingList.getLabel());
}
The corresponding POJO should be something like that :
相应的 POJO 应该是这样的:
public class ShoppingList {
int id;
String label;
boolean current;
int nb_reference;
//Setters & Getters !!!!!
}
Hope it helps !
希望能帮助到你 !
回答by Valentyn Kolesnikov
Underscore-javalibrary can convert json string to hash map. I am the maintainer of the project.
Underscore-java库可以将 json 字符串转换为哈希映射。我是项目的维护者。
Code example:
代码示例:
import com.github.underscore.lodash.U;
import java.util.*;
public class Main {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String json = "{"
+ " \"data\" :"
+ " {"
+ " \"field1\" : \"value1\","
+ " \"field2\" : \"value2\""
+ " }"
+ "}";
Map<String, Object> data = (Map) U.get((Map<String, Object>) U.fromJson(json), "data");
System.out.println(data);
// {field1=value1, field2=value2}
}
}