用Gson将JSON数组解析成java.util.List [英] Parsing JSON array into java.util.List with Gson

查看:101
本文介绍了用Gson将JSON数组解析成java.util.List的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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)

您只需获取 输入 List< String> 键入 ,然后将JSON数组解析为类型,像这样:

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

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

In your case yourJson is a JsonElement, but it could also be a String, any Reader or a JsonReader.

You may want to take a look at Gson API documentation.

这篇关于用Gson将JSON数组解析成java.util.List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆