java - Gson 反序列化不一致的数据类型
问题描述
我正在使用 JSONObject 将此 xml 转换为 Json 字符串。然后我使用 Gson 将此 Json 字符串转换为 POJO。
这个 XML:
<?xml version="1.0" encoding="UTF-8"?>
<History total="2" pageSize="2" pageStart="0">
<Asset href="/SomePath/continues" id="Story:12345:6789">
<Attribute name="Number">S-12345</Attribute>
<Attribute name="ChangeDate">2017-02-06T15:50:00.180</Attribute>
<Attribute name="Status.Name">Done</Attribute>
<Attribute name="Owners.Name">
<Value>Joe Smith</Value>
</Attribute>
</Asset>
<Asset href="/SomePath/continues" id="Story:9876:54321">
<Attribute name="Number">S-67890</Attribute>
<Attribute name="ChangeDate">2017-04-04T09:46:10.780</Attribute>
<Attribute name="Status.Name">Done</Attribute>
<Attribute name="Owners.Name">
<Value>Joe Smith</Value>
<Value>Tom Fong</Value>
</Attribute>
</Asset>
</History>
变成这样:
{
"History":{
"total":2,
"pageStart":0,
"pageSize":2,
"Asset":[
{
"Attribute":[
{
"name":"Number",
"content":"S-12345"
},
{
"name":"ChangeDate",
"content":"2017-02-06T15:50:00.180"
},
{
"name":"Status.Name",
"content":"Done"
},
{
"name":"Owners.Name",
**"Value":"Joe Smith"**
}
],
"href":"/SomePath/continues",
"id":"Story:12345:6789"
},
{
"Attribute":[
{
"name":"Number",
"content":"S-67890"
},
{
"name":"ChangeDate",
"content":"2017-04-04T09:46:10.780"
},
{
"name":"Status.Name",
"content":"Done"
},
{
"name":"Owners.Name",
**"Value":[
"Joe Smith",
"Tom Fong"
]**
}
],
"href":"/SomePath/continues",
"id":"Story:9876:54321"
}
]
}
}
问题出现在(“值”)标签上。有时它们只是一个字符串,有时它们是一个数组。
我一直在阅读 Gson 中的 TypeTokens,这是反序列化这种不一致数据类型的唯一方法吗?
我的班级是这样设置的:
public class QueryResults{
History History;
//Get/Sets
}
public class History{
long pageSize;
int pageStart;
long total;
List<Asset> Asset;
}
public class Asset{
String href;
String id;
List<Attribute> Attribute;
}
public class Attribute{
private String name;
private String content;
private Value value;
}
private class Value{
private List<String> names;
private String name;
}
我尝试在 Value 类中包含(如图所示)一个 String 变量和一个 List 变量。然后我有一个空检查,希望 gson 会选择正确的,但这没有用。
对此我完全没有任何建议吗?
我应该注意..我无法控制这些数据。
解决方案
推荐阅读
- javascript - 滚动事件监听器在 javascript 中不起作用
- django - 在 Django 中按类别而不是按产品搜索
- javascript - 将短语列表从大多数打印到列表频繁短语
- json - 在 SwiftUI 中解码汇率 JSON
- tokenize - Huggingface 的 BERT 标记器未添加填充标记
- python - 如何使用python查找成对的卡片包列表
- vue.js - 如何解决“预期分号”警告(css-semicolonexpected)
- python - Python DataFrame:每行的反距离概率
- clojure - Clojure-tagged literals::Raise an error-No dispatch macro for it
- php - 每个 IP 和日期的唯一访问