繁体   English   中英

GSON fromJson 未将值分配给 Java 字段

[英]GSON fromJson is not assigning values to the Java fields

我有一个 Json 字符串"{"value":"3A72fd4ccb-1980-26cf-8db3-9eaadf1205c2"}" ,同时将相同的字符串传递给以下代码:

Gson headerGson = new GsonBuilder().create();
Object  ob = headerGson.fromJson(jsonStr, cl);

结果 object 没有被分配给“值”是 json 字符串。 When I tried to print the object field using ReflectionAPI I got: The fields are:value Corresponding field type --> class java.lang.String Corresponding value is --> null

我在 fromJson 方法中作为“cl”传递的 java class 如下:

@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"} 因此,当您执行方法headerGson.fromJson(jsonStr, cl)时,Gson 试图在AttributedURI class 中查找MessageID字段,这显然不存在。 要反序列化您的 json,您可以将AttributedURI包装在其他 class 中。 例如:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM