使用 Gson 将 JSON 数组解析为 java.util.List [英] Parsing JSON array into java.util.List with Gson
问题描述
我有一个名为 "mapping"
的 JsonObject
,其内容如下:
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"
]
}
我知道我可以通过以下方式获取数组 "servers"
:
I know I can get the array "servers"
with:
mapping.get("servers").getAsJsonArray()
现在我想将 JsonArray
解析为 java.util.List
...
And now I want to parse that JsonArray
into a java.util.List
...
最简单的方法是什么?
推荐答案
绝对最简单的方法是使用 Gson 的默认解析函数 fromJson()
.
Definitely the easiest way to do that is using Gson's default parsing function fromJson()
.
当您需要反序列化为任何ParameterizedType
(例如,任何 List
),即 fromJson(JsonElement json, Type typeOfT)
.
There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType
(e.g., any List
), which is fromJson(JsonElement json, Type typeOfT)
.
就您而言,您只需要获取 Type
的 List
然后将 JSON 数组解析为该 Type
,如下所示:
In your case, you just need to get the Type
of a List<String>
and then parse the JSON array into that Type
, 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);
在你的情况下 yourJson
是一个 JsonElement
,但也可以是 String
,任何Reader
或 JsonReader
.
In your case yourJson
is a JsonElement
, but it could also be a String
, any Reader
or a JsonReader
.
您可能需要查看 Gson API 文档.
这篇关于使用 Gson 将 JSON 数组解析为 java.util.List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!