gpt4 book ai didi

java - 如何反序列化 Array google-gson 中的 Array

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:09:53 26 4
gpt4 key购买 nike

我有这样的 JSON:

{
"Answers":
[
[
{"Locale":"Ru","Name":"Name1"},
{"Locale":"En","Name":"Name2"}
],
[
{"Locale":"Ru","Name":"Name3"},
{"Locale":"En","Name":"Name4"}
]
]
}

如您所见,我在数组中有数组。如何在 Android ( https://code.google.com/p/google-gson/ ) 上使用 google-gson 库将此类 JSON 结构反序列化为对象?

最佳答案

Json 格式后我们得到这样的东西:

我的对象

public class MyObject {
public List<List<Part>> Answers;

public List<List<Part>> getAnswers() {
return Answers;
}
}

部分

public class Part {
private String Locale;
private String Name;

public String getLocale() {
return Locale;
}
public String getName() {
return Name;
}

}

主要

public static void main(String[] args) {
String str = " {" +
" \"Answers\": [[{" +
" \"Locale\": \"Ru\"," +
" \"Name\": \"Name1\"" +
" }," +
" {" +
" \"Locale\": \"En\"," +
" \"Name\": \"Name2\"" +
" }]," +
" [{" +
" \"Locale\": \"Ru\"," +
" \"Name\": \"Name3\"" +
" }," +
" {" +
" \"Locale\": \"En\"," +
" \"Name\": \"Name4\"" +
" }]]" +
" }";

Gson gson = new Gson();

MyObject obj = gson.fromJson(str, MyObject.class);

List<List<Part>> answers = obj.getAnswers();

for(List<Part> parts : answers){
for(Part part : parts){
System.out.println("locale: " + part.getLocale() + "; name: " + part.getName());
}
}

}

输出:

locale: Ru; name: Name1
locale: En; name: Name2
locale: Ru; name: Name3
locale: En; name: Name4

关于java - 如何反序列化 Array google-gson 中的 Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19154851/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com