从 json 编码/解码到 java.util.Map 的库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2496494/
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
Library to encode/decode from json to java.util.Map?
提问by OscarRyz
Does anyone knows a java library that could easily encode java Maps into json objects and the other way around?
有谁知道一个可以轻松将 java Maps 编码为 json 对象的 java 库,反之亦然?
UPDATE
更新
For reasons couldn't explain ( and I hate sometimes ) I can't use generics on my environment.
由于无法解释的原因(有时我讨厌)我不能在我的环境中使用泛型。
What' I'm trying to do is to have something like this:
我想做的是有这样的事情:
Map a = new HashMap();
a.put( "name", "Oscar" );
Map b = new HashMap();
b.put( "name", "MyBoss");
a.put( "boss", b ) ;
List list = new ArrayList();
list.add( a );
list.add( b );
String json = toJson( list );
// and create the json:
/*
[
{
"name":"Oscar",
"boss":{
"name":"MyBoss"
}
},
{
"name":"MyBoss"
}
]
*/
And be able to have it again as a list of maps
并且能够再次将其作为地图列表
List aList = ( List ) fromJson( jsonStirng );
采纳答案by Taylor Leese
JSON-Simplelooks relatively easy to use (examples below).
JSON-Simple看起来相对容易使用(示例如下)。
Map to JSON:
映射到 JSON:
Map map = new HashMap();
map.put("name", "foo");
map.put("nickname", "bar");
String jsonText = JSONValue.toJSONString(map);
JSON to List/Map:
JSON 到列表/映射:
String s = yourJsonString;
List list = (JSONArray) JSONValue.parse(s);
Map map = (JSONObject) list.get(0);
回答by Lluis Martinez
We use http://json-lib.sourceforge.net/in our project, it works just fine.
我们在我们的项目中使用http://json-lib.sourceforge.net/,它工作得很好。
回答by BalusC
You can use Google Gsonfor that. It has excellent support for Generic types.
你可以使用谷歌 Gson。它对Generic types有很好的支持。
Here's an SSCCE:
这是一个SSCCE:
package com.stackoverflow.q2496494;
import java.util.LinkedHashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Test {
public static void main(String... args) {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
Gson gson = new Gson();
// Serialize.
String json = gson.toJson(map);
System.out.println(json); // {"key1":"value1","key2":"value2","key3":"value3"}
// Deserialize.
Map<String, String> map2 = gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType());
System.out.println(map2); // {key1=value1, key2=value2, key3=value3}
}
}
回答by Buhake Sindi
You can view the site from Json.orgfor the list of good JSON libraries in Java.
您可以从Json.org查看站点以获取 Java 中优秀 JSON 库的列表。
JSon.org's own implementationJSONObject
can do just that.
From their JavaDoC
Json.org 自己的实现JSONObject
可以做到这一点。来自他们的 JavaDoC
/**
* Construct a JSONObject from a Map.
*
* @param map A map object that can be used to initialize the contents of
* the JSONObject.
*/
public JSONObject(Map map);
you can do
你可以做
JSONObject json = new JSONObject(map);
To convert JSON String back to object....
将 JSON 字符串转换回对象....
String jsonString = "{\"name\" : \"some name\", \"age\" : 10}";
JSONObject json = new JSONObject(jsonString);
and you can access values like:
您可以访问以下值:
int age = json.getInt("age");
Constructor JavaDoC
构造函数 JavaDoC
Construct a JSONObject from a source JSON text string. This is the most commonly used JSONObject constructor.
Parameters: source A string beginning with
{
(left brace) and ending with}
(right brace).
从源 JSON 文本字符串构造一个 JSONObject。这是最常用的 JSONObject 构造函数。
参数: source 以
{
(左大括号)开头并以}
(右大括号)结尾的字符串。
回答by StaxMan
I guess the real question would be which JSON library (from org.json's page) would NOT allow doing this. As far as I know every single library there would allow this in some form. So every library mentioned so far works.
我想真正的问题是哪个 JSON 库(来自 org.json 的页面)不允许这样做。据我所知,那里的每个图书馆都会以某种形式允许这样做。所以到目前为止提到的每个图书馆都有效。
And to add some information, Hymansonworks very well with all kinds of data including basic Maps and Lists:
为了添加一些信息,Hymanson可以很好地处理各种数据,包括基本的地图和列表:
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValue(list);
List listOfMaps = mapper.readValue(json, List.class);
which would handle this particular case. While generic type information can be used, it is optional when using "natural" binding to JDK container types.
这将处理这种特殊情况。虽然可以使用泛型类型信息,但在对 JDK 容器类型使用“自然”绑定时它是可选的。
回答by Arun Pratap Singh
When using google gson.
使用谷歌 gson 时。
var getRowData =
[{
"dayOfWeek": "Sun",
"date": "11-Mar-2012",
"los": "1",
"specialEvent": "",
"lrv": "0"
},
{
"dayOfWeek": "Mon",
"date": "",
"los": "2",
"specialEvent": "",
"lrv": "0.16"
}];
JsonElement root = new JsonParser().parse(request.getParameter("getRowData"));
JsonArray jsonArray = root.getAsJsonArray();
JsonObject jsonObject1 = jsonArray.get(0).getAsJsonObject();
String dayOfWeek = jsonObject1.get("dayOfWeek").toString();
// when using Hymanson
// 当使用Hyman逊时
JsonFactory f = new JsonFactory();
ObjectMapper mapper = new ObjectMapper();
JsonParser jp = f.createJsonParser(getRowData);
// advance stream to START_ARRAY first:
jp.nextToken();
// and then each time, advance to opening START_OBJECT
while (jp.nextToken() == JsonToken.START_OBJECT) {
Map<String,Object> userData = mapper.readValue(jp, Map.class);
userData.get("dayOfWeek");
// process
// after binding, stream points to closing END_OBJECT
}