java使用未知键反序列化JSON
我正在尝试用未知键反序列化JSON对象(来自JIRA REST APIcreateMeta)
{
"expand": "projects",
"projects": [
{
"self": "http://www.example.com/jira/rest/api/2/project/EX",
"id": "10000",
"key": "EX",
"name": "Example Project",
"avatarUrls": {
"24x24": "http://www.example.com/jira/secure/projectavatar?size=small&pid=10000&avatarId=10011",
"16x16": "http://www.example.com/jira/secure/projectavatar?size=xsmall&pid=10000&avatarId=10011",
"32x32": "http://www.example.com/jira/secure/projectavatar?size=medium&pid=10000&avatarId=10011",
"48x48": "http://www.example.com/jira/secure/projectavatar?pid=10000&avatarId=10011"
},
"issuetypes": [
{
"self": "http://www.example.com/jira/rest/api/2/issueType/1",
"id": "1",
"description": "An error in the code",
"iconUrl": "http://www.example.com/jira/images/icons/issuetypes/bug.png",
"name": "Bug",
"subtask": false,
"fields": {
"issuetype": {
"required": true,
"name": "Issue Type",
"hasDefaultValue": false,
"operations": [
"set"
]
}
}
}
]
}
]
}
我的问题是:我不知道进入“字段”的键(在下面的示例中为“issuetype”、“summary”、“description”、“customfield_12345”)
"fields": {
"issuetype": { ... },
"summary": { ... },
"description": { ... },
"customfield_12345": { ... }
}
如果我能在我的POJO中将其反序列化为一个数组,其中键为“id”,那就太棒了,因此上面的示例如下所示:
class IssueType {
...
public List<Field> fields;
...
}
class Field {
public String id; // the key from the JSON object e.g. "issuetype"
public boolean required;
public String name;
...
}
有没有一种方法可以实现这一点并将其包装到我的模型中?我希望我的问题是可以理解的:)
# 1 楼答案
我知道这是个老问题,但我也有这个问题,而且有结果。。 Meybe将来会帮助别人:)
我用未知的答案回答:
所以我还检查了jsonElement是否为jsonArray,它是否为空。 如果是jsonObject,我们有数据
# 2 楼答案
有一个非常适合Java的JSON库,可以将任何有效的JSON转换为Java POJOhttp://www.json.org/java/
# 3 楼答案
如果事先不知道键,就无法定义适当的字段。你最好使用
Map<String,Object>
如果实际上有几个类型,您可以为这些类型标识字段集合,那么可以编写一个自定义反序列化程序来检查字段并返回适当类型的对象