更新时间:2023-02-15 17:33:03
您可以使用自定义变压器来实现.根据Flexjson页面转换器,是:
You can achieve this by using a Custom Transformer. As per Flexjson page transformer is:
负责决定如何将传入的对象转换为 JSON,对JSONContext对象进行适当的调用以输出 JSON,和/或在转换过程中传递对象.
Responsible for deciding how to translate the passed in object to JSON, making the appropriate calls on the JSONContext object to output the JSON, and/or passing the object along the transformation process.
Flexjson为此提供了一个抽象类 AbstractTransformer ;扩展和覆盖transform(Object object)
可以自己处理转换.
Flexjson has provided an abstract class AbstractTransformer for this purpose; Extend and override transform(Object object)
to handle the transformation by yourself.
下面粘贴的是FieldNameTransformer
的代码,该代码是我编写的用于手动指定字段名称s的代码:
Pasted below is the code of FieldNameTransformer
which I wrote for specifying the field name s manually:
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(object.toString());
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;
}
}
以下是如何使用此自定义转换器:
Following is how to use this custom transformer:
JSONSerializer serializer = new JSONSerializer().transform(new FieldNameTransformer("Name"), "name");
其中原始字段的名称为"name",但在json输出中,它将替换为Name.
where original field's name is 'name' but in json ouput it will be replaced with Name.
采样:
{"Name":"Abdul Kareem"}