使用 Gson 将 JSON 数组解析为 java.util.List
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18544133/
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
Parsing JSON array into java.util.List with Gson
提问by Abel Callejo
I have a JsonObject
named "mapping"
with the following content:
我有一个具有以下内容的JsonObject
命名"mapping"
:
{
"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:
我知道我可以通过以下方式获取数组"servers"
:
mapping.get("servers").getAsJsonArray()
And now I want to parse that JsonArray
into a java.util.List
...
现在我想把它解析JsonArray
成一个java.util.List
......
What is the easiest way to do this?
什么是最简单的方法来做到这一点?
采纳答案by MikO
Definitely the easiest way to do that is using Gson's default parsing function fromJson()
.
绝对最简单的方法是使用 Gson 的默认解析函数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)
.
还有当你需要反序列化到任何合适的这一功能的实现ParameterizedType
(例如,任何List
),这是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:
在您的情况下,您只需要获取Type
aList<String>
然后将 JSON 数组解析为 that 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);
In your case yourJson
is a JsonElement
, but it could also be a String
, any Reader
or a JsonReader
.
在您的情况下yourJson
是 a JsonElement
,但它也可以是 a String
、 anyReader
或 a JsonReader
。
You may want to take a look at Gson API documentation.
您可能需要查看Gson API 文档。
回答by Prateek
Below code is using com.google.gson.JsonArray
.
I have printed the number of element in list as well as the elements in List
下面的代码正在使用com.google.gson.JsonArray
. 我已经打印了列表中的元素数量以及列表中的元素
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String str = "{ "+
"\"client\":\"127.0.0.1\"," +
"\"servers\":[" +
" \"8.8.8.8\"," +
" \"8.8.4.4\"," +
" \"156.154.70.1\"," +
" \"156.154.71.1\" " +
" ]" +
"}";
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(str);
JsonArray jsonArr = jo.getAsJsonArray("servers");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
输出
List size is : 4
List Elements are : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]
回答by Hoang
I read solution from official website of Gson at here
我在这里阅读了 Gson 官方网站上的解决方案
And this code for you:
而这个代码给你:
String json = "{"client":"127.0.0.1","servers":["8.8.8.8","8.8.4.4","156.154.70.1","156.154.71.1"]}";
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
JsonArray jsonArray = jsonObject.getAsJsonArray("servers");
String[] arrName = new Gson().fromJson(jsonArray, String[].class);
List<String> lstName = new ArrayList<>();
lstName = Arrays.asList(arrName);
for (String str : lstName) {
System.out.println(str);
}
Result show on monitor:
结果显示在监视器上:
8.8.8.8
8.8.4.4
156.154.70.1
156.154.71.1
回答by Gene Bo
I was able to get the list mapping to work with just using @SerializedName
for all fields.. no logic around Type
was necessary.
我能够让列表映射仅@SerializedName
用于所有字段.. 不需要任何逻辑Type
。
Running the code - in step #4 below- through the debugger, I am able to observe that the List<ContentImage> mGalleryImages
object populated with the JSON data
运行代码 -在下面的第 4 步中- 通过调试器,我能够观察到List<ContentImage> mGalleryImages
用 JSON 数据填充的对象
Here's an example:
下面是一个例子:
1. The JSON
1. JSON
{
"name": "Some House",
"gallery": [
{
"description": "Nice 300sqft. den.jpg",
"photo_url": "image/den.jpg"
},
{
"description": "Floor Plan",
"photo_url": "image/floor_plan.jpg"
}
]
}
2. Java class with the List
2.带有List的Java类
public class FocusArea {
@SerializedName("name")
private String mName;
@SerializedName("gallery")
private List<ContentImage> mGalleryImages;
}
3. Java class for the List items
3. List 项的 Java 类
public class ContentImage {
@SerializedName("description")
private String mDescription;
@SerializedName("photo_url")
private String mPhotoUrl;
// getters/setters ..
}
4. The Java code that processes the JSON
4. 处理 JSON 的 Java 代码
for (String key : focusAreaKeys) {
JsonElement sectionElement = sectionsJsonObject.get(key);
FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);
}
回答by Alex Moore-Niemi
Given you start with mapping.get("servers").getAsJsonArray()
, if you have access to GuavaStreams
, you can do the below one-liner:
鉴于您从 开始mapping.get("servers").getAsJsonArray()
,如果您可以访问GuavaStreams
,则可以执行以下单行操作:
List<String> servers = Streams.stream(jsonArray.iterator())
.map(je -> je.getAsString())
.collect(Collectors.toList());
Note StreamSupport
won't be able to work on JsonElement
type, so it is insufficient.
NoteStreamSupport
将无法处理JsonElement
类型,因此它是不够的。