用Gson将JSON数组解析成java.util.List [英] Parsing JSON array into java.util.List with Gson
问题描述
我有一个 JsonObject
,名为mapping
,其中包含以下内容:
{
client:127.0.0.1,
servers:[
8.8.8.8,
8.8.4.4,
156.154.70.1,
156.154.71.1
]
}
我知道我可以通过以下方式获得数组
servers
mapping.get(servers)。getAsJsonArray()
现在我想将
JsonArray
解析为java.util.List
。 ..
最简单的方法是什么?
解决方案当然,最简单的方法是使用Gson的默认解析函数
fromJson()
。
这个函数的实现适用于需要反序列化到任何
ParameterizedType
(例如,任何List
),其中fromJson(JsonElement json,Type typeOfT)
。
您只需获取
输入
,然后将JSON数组解析为List< String>
键入类型
,像这样:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
JsonElement yourJson = mapping.get(servers);
Type listType = new TypeToken< List< String>>(){} .getType();
列表< String> yourList = new Gson()。fromJson(yourJson,listType);
您的情况
yourJson
是一个JsonElement
,但它也可以是字符串
,任何阅读器
或JsonReader
。
您可能想看一看 Gson API文档。
I have a
JsonObject
named"mapping"
with the following content:{ "client": "127.0.0.1", "servers": [ "8.8.8.8", "8.8.4.4", "156.154.70.1", "156.154.71.1" ] }
I know I can get the array
"servers"
with:mapping.get("servers").getAsJsonArray()
And now I want to parse that
JsonArray
into ajava.util.List
...What is the easiest way to do this?
解决方案Definitely the easiest way to do that is using Gson's default parsing function
fromJson()
.There is an implementation of this function suitable for when you need to deserialize into any
ParameterizedType
(e.g., anyList
), which isfromJson(JsonElement json, Type typeOfT)
.In your case, you just need to get the
Type
of aList<String>
and then parse the JSON array into thatType
, like this:import java.lang.reflect.Type; import com.google.gson.reflect.TypeToken; JsonElement yourJson = mapping.get("servers"); Type listType = new TypeToken<List<String>>() {}.getType(); List<String> yourList = new Gson().fromJson(yourJson, listType);
In your case
yourJson
is aJsonElement
, but it could also be aString
, anyReader
or aJsonReader
.You may want to take a look at Gson API documentation.
这篇关于用Gson将JSON数组解析成java.util.List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!