java - 当对象名称为整数时,Java GSON 反序列化 JSON
问题描述
首先,我知道如何反序列化 JSON 对象。我遇到的具体问题是我有一个 Json 对象,其中包含名为的数组"1", "2", "3"
等,但在 Java 中我无法声明变量ArrayList<AnotherObject> 1;
有没有比手动替换数字更好的方法?
Json(大大减少):
{
"object": {
"1": [{...}],
"2": [{...}],
"3": [{...}],
"4": [{...}],
"5": [{...}],
"6": [{...}],
"7": [{...}]
}
}
提前致谢
解决方案
这是您可以GSON
用来反序列化 JSON 的方法:
public static void main(String[] args) {
final String json = "{\n" +
" \"object\": {\n" +
" \"1\": [{ \"id\" : 111 }],\n" +
" \"2\": [{ \"id\" : 222 }],\n" +
" \"3\": [{ \"id\" : 333 }]\n" +
" }\n" +
"}\n";
final Gson gson = new GsonBuilder()
.create();
final ObjectWrapper value = gson.fromJson(json, ObjectWrapper.class);
System.out.println(value.object);
System.out.println(value.object.keySet());
System.out.println(value.object.get(1));
}
// This is top-most object we want to deserialize from JSON
static class ObjectWrapper {
// Didn't bother about proper naming while it is better to give a meaningful name here
private Map<Integer, List<Element>> object;
}
static class Element {
// Added this attribute to demonstrate that objects within array are properly read
private int id;
@Override
public String toString() {
return "{id=" + id + "}";
}
}
推荐阅读
- javascript - 如何使用 this.val() 从列表中的输入中提取值?
- java - 如何仅对其中一个字段与 Lucene 7.5.0 中的特定值匹配的文档执行查询搜索?
- azure - 获取 azure powershell 上其标签以(或包含)特定字符串开头的所有资源 - Azure Powershell
- dart - 颤振 - Map 中的 Dart Map 调用为 null
- json - Comparing Json data. Python 3
- c - 为什么`pLQ->tail`是一个空指针?
- sql - 将多个日期行合并为单个并计数标准 SQL
- javascript - 通配符 * 响应所有请求的路由
- excel - VBA查找方法设置范围从字符串不准确
- c# - 如何使用不同的变量多次启动一个方法