Gson json使用自定义FieldNamingPolicy

时间:2017-04-05 10:15:43

标签: android json xml gson

在一个Android项目中,我创建了从xsd文件中提取的类,看起来像这样

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LoginUserResponse1Document", propOrder = {
    "lgnUsrRspn"
})
public class LoginUserResponse1Document {

    @XmlElement(name = "LgnUsrRspn", required = true)
    protected LoginUserResponseV01 lgnUsrRspn;

    /**
     * Gets the value of the lgnUsrRspn property.
     * 
     * @return
     *     possible object is
     *     {@link LoginUserResponseV01 }
     *     
     */
    public LoginUserResponseV01 getLgnUsrRspn() {
        return lgnUsrRspn;
    }

    /**
     * Sets the value of the lgnUsrRspn property.
     * 
     * @param value
     *     allowed object is
     *     {@link LoginUserResponseV01 }
     *     
     */
    public void setLgnUsrRspn(LoginUserResponseV01 value) {
        this.lgnUsrRspn = value;
    }
}

使用的api使用@XmlElement(name = "LgnUsrRspn", required = true)中出现的名称,例如在其中一个请求中,我在json中得到响应,如下所示:

{
  "LgnUsrRspn": {
    "Hdr": {
      "XchgId": "7403AC2E976D46968F6B4839E2FCB7A6",
      "DtTm": "2017-04-05T09:20:47.593+0000",
      "NxtFlow": "LOG"
    },
    "LgnUsr": {
      "Rslt": {
        "RsltStts": "DECL",
        "RsltRsn": ""
      }
    }
  }
}

我也有这个类来处理json转换

public class JsonBuilder {

    private JsonBuilder(){
    }

    public static String toJson(Object pojo){
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
        Gson gson = gsonBuilder.create();
        return gson.toJson(pojo);
    }

    public static Object fromJson(String json, Class type){
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
        Gson gson = gsonBuilder.create();
        return gson.fromJson(json, type);
    }
}

我的问题是,是否有一种方法可以创建自定义FieldNamingPolicy以与GsonBuilder一起使用,或者我可以使用@XmlElement(name = "LgnUsrRspn", required = true)中的名称

的方式

1 个答案:

答案 0 :(得分:2)

您可以使用允许您通过自己的setFieldNamingStrategy()实施的FieldNamingStrategy

例如,

public class XsdAnnotation implements FieldNamingStrategy {

    @Override
    public String translateName(Field field) {
        XmlElement fieldNamingPolicy = field.getAnnotation(XmlElement.class);
        return fieldNamingPolicy.name();
    }
}

但我建议将其与@SerializedName一起使用。