首页 > 解决方案 > 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;
}

}

请让我知道我在这里缺少什么。

标签: javajsongson

解决方案


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

推荐阅读