2014-03-13 41 views
0

所以我有這樣的代碼:是否有可能獲取@XmlElement名稱值而不是對象到Json轉換的變量名稱?

<xs:element name="Headers"> 
    <xs:annotation> 
     <xs:documentation>Headers Object</xs:documentation> 
    </xs:annotation> 
    <xs:complexType> 
     <xs:sequence>    
      <xs:element name="content-type" type="xs:string" minOccurs="0" /> 
      </xs:sequence> 
    </xs:complexType> 
</xs:element> 

當我創建類的頭,我得到這個的內容類型元素:

@XmlElement(name = "content-type") 
protected String contentType; 

我使用GSON將對象轉換爲JSON :

"headers": [{   
    "contentType": "application/x-www-form-urlencoded", 
}], 

我需要的是我在XSD文件有它得到的contentType元素,所以我的問題是,如果有任何機會搶@XmlElement名稱值和,使用T在轉換帽子而不是變量名稱。我也試過xstream庫,但得到相同的結果。

在此先感謝。

+0

'@SerializedName( 「內容類型」)' –

+0

非常感謝你的人! – ZakRoM

回答

0

是的,這是可能的。 對於這個不需要修改xsd來添加@SerializedName(「content-type」),如果xsd非常大,這也不是時間。

PS:我爲此使用Gson API。

GsonBuilder gson = new GsonBuilder(); 
gson.setFieldNamingStrategy(new CustomFieldNamePolicy()); 

而且CustomFieldNamePolicy類可以被定義爲:

public class CustomFieldNamePolicy implements FieldNamingStrategy{ 

    @Override 
    public String translateName(Field paramField) { 

     Annotation annotationName = null; 

     if(null != (annotationName = paramField.getAnnotation(XmlElement.class))){ 
      return ((XmlElement) annotationName).name(); 
     }else if(null != (annotationName = paramField.getAnnotation(XmlAttribute.class))){ 
      return ((XmlAttribute)annotationName).name(); 
     } 
     return paramField.getName(); 
    } 
} 
相關問題