我有一个Json字符串"{"value":"3A72fd4ccb-1980-26cf-8db3-9eaadf1205c2"}"
,同时将相同的字符串传递给以下代码:
Gson headerGson = new GsonBuilder().create();
Object ob = headerGson.fromJson(jsonStr, cl);
结果对象未分配给json字符串的“值”。当我尝试使用ReflectionAPI打印对象字段时,得到了:字段是:值对应的字段类型->类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;
}
}
[请让我知道我在这里缺少什么。
Class 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);