java - GSON fromJson 没有为 Java 字段赋值
问题描述
我有一个 Json string "{"value":"3A72fd4ccb-1980-26cf-8db3-9eaadf1205c2"}"
,同时将相同的字符串传递给以下代码:
Gson headerGson = new GsonBuilder().create();
Object ob = headerGson.fromJson(jsonStr, cl);
结果对象未分配给“值”是 json 字符串。当我尝试使用 ReflectionAPI 打印对象字段时,我得到:字段是 :value 对应的字段类型 --> 类 java.lang.String 对应的值是 --> null
我在 fromJson 方法中作为“cl”传递的 java 类如下:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AttributedURI", propOrder = {
"value"
})
public class AttributedURI {
@XmlValue
@XmlSchemaType(name = "anyURI")
protected String value;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets a map that contains attributes that aren't bound to any typed property on this class.
*
* <p>
* the map is keyed by the name of the attribute and
* the value is the string value of the attribute.
*
* the map returned by this method is live, and you can add new attribute
* by updating the map directly. Because of this design, there's no setter.
*
*
* @return
* always non-null
*/
public Map<QName, String> getOtherAttributes() {
return otherAttributes;
}
}
请让我知道我在这里缺少什么。
解决方案
类AttributedURI
是代表你的 json: 的内部部分{"value":"3A72fd4ccb-1980-26cf-8db3-9eaadf1205c2"}
。因此,当您执行 method 时headerGson.fromJson(jsonStr, cl)
,Gson 正在尝试MessageID
在类中查找字段AttributedURI
,这显然不存在。要反序列化您的 json,您可以包装AttributedURI
在其他类中。例如:
public class OuterClass {
@SerializedName("MessageID")
private AttributedURI messageID;
public AttributedURI getMessageID(){
return messageID;
}
}
我也怀疑你在这里需要 XML 注释:afaik,GSON 不需要它们。
另外,Gson#fromJson
是通用方法,因此您可以编写:
OuterClass ob = headerGson.fromJson(jsonStr, OuterClass.class);
推荐阅读
- firebase - URL 重写会使 Firebase 云功能响应来自我的自定义域吗?
- amazon-web-services - 如何通过 API 检索 AWS RDS 数据库实例中的所有数据库列表?
- python - websocket握手期间的Django-channels错误:意外响应代码:404本地
- localdb - 是 x86 机器的 sqllocaldb.msi 2019
- javascript - 如何从 JSON 请求中删除不需要的字符
- layer - 如何在mapboxgl内的图层中使用Mapbox的tileset Id?
- java - 如何使用 Google Drive API v3 获取组织的 Google Workspace 中所有用户的所有文件?
- css - 所有 HTML 树的第一个元素的 CSS 属性
- java - timeDifference(DateTime) 对于 OpenNTF Domino API 中的 DateTime 类型不明确
- reactjs - 如何使用打字稿编写 es6 onchange 方法并做出反应?