问题描述
我使用FlexJson进行序列化,唯一的问题是它会生成小写的字段名,而我需要它们以大写开头:
I use FlexJson for serialization, the only problem is that it generates the field names lower case while I need them to start with upper case:
class Person
{
String name;
public String getName() { return name;}
}
序列化时,该字段序列化为name
,而我需要将其序列化为Name
.
When serialized the field is serialized as name
, while I need it to be Name
.
如何指定输出字段名称?我可以使用一些属性来指定所需的序列化名称吗?
How can I specify the output field name? Is there some attribute I can put to specify the required serialization name?
推荐答案
您可以使用自定义变压器来实现.根据Flexjson页面转换器,是:
You can achieve this by using a Custom Transformer. As per Flexjson page transformer is:
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"}
这篇关于使用Flexjson更改属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!