我有一个名为"mapping"JsonObject,内容如下:

{
    "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()

现在我想把这个JsonArray分为一个java.util.List...

做这件事最简单的方法是什么?

推荐答案

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., any List), which is fromJson(JsonElement json, Type typeOfT).

在您的例子中,只需要获得List<String>Type,然后将JSON数组解析为Type,如下所示:

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);

在你的例子中,yourJsonJsonElement,但也可以是String,任何ReaderJsonReader.

你可能想看看Gson API documentation.

Json相关问答推荐

无法根据vega规范中的条件设置文本 colored颜色

合并二维数组的Jolt表达式

JSON:将项';S键/名称移动到属性中,并使用JQ将其转换为数组

如何使用Aeson解码带有Unicode字符的JSON文件?

如何在Haskell中解析JSON,其中字段的名称可以是多个值之一,但应该转换为单个Haskell类型?

Jolt Spec 跳过数组中的第一个元素

如何在 Android Studio 中将 List 字段作为空列表[]返回?

使用 SwiftUI 在 API 调用中解码嵌套 JSON 响应时遇到问题

当值包含ansible中的字符串时解析json值

在 Perl Mojolicious 中呈现 JSON 时防止转义字符

如何让 JSON.NET 忽略对象关系?

如何在 Eclipse 中安装和使用 JSON 编辑器?

如何使用 json.net 将数据表转换为 json 字符串?

如何通过 NSJSONSerialization 在 JSON 中包含空值?

Jsonpath 与 Jackson 或 Gson

Json.NET 是否缓存类型的序列化信息?

如何将 MongoDB 查询转换为 JSON?

Microsoft.Net.Http 与 Microsoft.AspNet.WebApi.Client

jq:按属性分组和键

如何从 github API 解析链接头