Java 使用 GSON 解析嵌套的 JSON 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19169754/
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 nested JSON data using GSON
提问by user2844485
I'm trying to parse some JSON data using gson in Java that has the following structure but by looking at examples online, I cannot find anything that does the job.
我正在尝试使用具有以下结构的 Java 中的 gson 解析一些 JSON 数据,但是通过查看在线示例,我找不到任何可以完成这项工作的内容。
Would anyone be able to assist?
有人可以提供帮助吗?
{
"data":{
"id":[
{
"stuff":{
},
"values":[
[
123,
456
],
[
123,
456
],
[
123,
456
],
],
"otherStuff":"blah"
}
]
}
}
采纳答案by MikO
You just need to create a Java class structure that represents the data in your JSON. In order to do that, I suggest you to copy your JSON into this online JSON Viewerand you'll see the structure of your JSON much clearer...
您只需要创建一个 Java 类结构来表示 JSON 中的数据。为此,我建议您将 JSON 复制到此在线 JSON 查看器中,您将更清楚地看到 JSON 的结构......
Basically you need these classes (pseudo-code):
基本上你需要这些类(伪代码):
class Response
Data data
class Data
List<ID> id
class ID
Stuff stuff
List<List<Integer>> values
String otherStuff
Note that attribute names in your classes must match the names of your JSON fields! You may add more attributes and classes according to your actual JSON structure... Also note that you need getters and setters for all your attributes!
请注意,类中的属性名称必须与 JSON 字段的名称匹配!你可以根据你的实际 JSON 结构添加更多的属性和类......另外请注意,你的所有属性都需要 getter 和 setter!
Finally, you just need to parse the JSON into your Java class structure with:
最后,您只需要使用以下命令将 JSON 解析为您的 Java 类结构:
Gson gson = new Gson();
Response response = gson.fromJson(yourJsonString, Response.class);
And that's it! Now you can access all your data within the response
object using the getters and setters...
就是这样!现在您可以response
使用 getter 和 setter访问对象中的所有数据...
For example, in order to access the first value 456
, you'll need to do:
例如,为了访问第一个 value 456
,您需要执行以下操作:
int value = response.getData().getId().get(0).getValues().get(0).get(1);
回答by Origineil
Depending on what you are trying to do. You could just setup a POJO heirarchy that matches your json
as seen here(Preferred method). Or, you could provide a custom deserializer. I only dealt with the id
data as I assumed it was the tricky implementation in question. Just step through the json
using the gson
types, and build up the data you are trying to represent. The Data
and Id
classes are just pojos
composed of and reflecting the properties in the original json
string.
取决于你想做什么。您可以设置一个与您json
在此处看到的相匹配的 POJO 层次结构(首选方法)。或者,您可以提供自定义反序列化器。我只处理id
数据,因为我认为这是有问题的棘手实现。只需逐步json
使用这些gson
类型,并构建您要表示的数据。在Data
和Id
类是刚刚pojos
组成的,并反映在原有的属性json
字符串。
public class MyDeserializer implements JsonDeserializer<Data>
{
@Override
public Data deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException
{
final Gson gson = new Gson();
final JsonObject obj = je.getAsJsonObject(); //our original full json string
final JsonElement dataElement = obj.get("data");
final JsonElement idElement = dataElement.getAsJsonObject().get("id");
final JsonArray idArray = idElement.getAsJsonArray();
final List<Id> parsedData = new ArrayList<>();
for (Object object : idArray)
{
final JsonObject jsonObject = (JsonObject) object;
//can pass this into constructor of Id or through a setter
final JsonObject stuff = jsonObject.get("stuff").getAsJsonObject();
final JsonArray valuesArray = jsonObject.getAsJsonArray("values");
final Id id = new Id();
for (Object value : valuesArray)
{
final JsonArray nestedArray = (JsonArray)value;
final Integer[] nest = gson.fromJson(nestedArray, Integer[].class);
id.addNestedValues(nest);
}
parsedData.add(id);
}
return new Data(parsedData);
}
}
}
Test:
测试:
@Test
public void testMethod1()
{
final String values = "[[123, 456], [987, 654]]";
final String id = "[ {stuff: { }, values: " + values + ", otherstuff: 'stuff2' }]";
final String jsonString = "{data: {id:" + id + "}}";
System.out.println(jsonString);
final Gson gson = new GsonBuilder().registerTypeAdapter(Data.class, new MyDeserializer()).create();
System.out.println(gson.fromJson(jsonString, Data.class));
}
Result:
结果:
Data{ids=[Id {nestedList=[[123, 456], [987, 654]]}]}
POJO:
POJO:
public class Data
{
private List<Id> ids;
public Data(List<Id> ids)
{
this.ids = ids;
}
@Override
public String toString()
{
return "Data{" + "ids=" + ids + '}';
}
}
public class Id
{
private List<Integer[]> nestedList;
public Id()
{
nestedList = new ArrayList<>();
}
public void addNestedValues(final Integer[] values)
{
nestedList.add(values);
}
@Override
public String toString()
{
final List<String> formattedOutput = new ArrayList();
for (Integer[] integers : nestedList)
{
formattedOutput.add(Arrays.asList(integers).toString());
}
return "Id {" + "nestedList=" + formattedOutput + '}';
}
}