我从这里找到了这段代码:Change property name with Flexjson
它适用于字符串数据类型,但似乎没有其他数据类型。有任何想法吗?
public class FieldNameTransformer extends AbstractTransformer {
private String transformedFieldName;
public FieldNameTransformer(String transformedFieldName) {
this.transformedFieldName = transformedFieldName;
}
public void transform(Object object) {
boolean setContext = false;
TypeContext typeContext = getContext().peekTypeContext();
//Write comma before starting to write field name if this
//isn't first property that is being transformed
if (!typeContext.isFirst())
getContext().writeComma();
typeContext.setFirst(false);
getContext().writeName(getTransformedFieldName());
getContext().writeQuoted((String) object);
if (setContext) {
getContext().writeCloseObject();
}
}
/***
* TRUE tells the JSONContext that this class will be handling
* the writing of our property name by itself.
*/
@Override
public Boolean isInline() {
return Boolean.TRUE;
}
public String getTransformedFieldName() {
return this.transformedFieldName;
}
}
这适用于文本字段,但如果我尝试将其应用于日期字段,则会非常不高兴。例如:
String JSON = new JSONSerializer()
.include("type", "createDate")
.exclude("*")
.transform(new DateTransformer("MM/dd/yyyy"), Date.class)
.transform(new FieldNameTransformer("new_json_property_name"),"createDate")
.serialize(stuff);
发生 JSONException 失败:尝试 deepSerialize 时出错
当我注释掉 transform new Field... 行时它工作正常,当我尝试更改类型字段时它工作正常,它是一个字符串。
尝试修改和 Int 时它也会失败,我希望其他所有内容都不是字符串。
如果有人熟悉 FlexJSON API 并且可以在这里为我指明正确的方向,我将非常感激。