Change property name with Flexjson

故事扮演 提交于 2019-11-30 18:41:25

问题


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;}
}

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?


回答1:


You can achieve this by using a Custom Transformer. As per Flexjson page transformer is:

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 has provided an abstract class AbstractTransformer for this purpose; Extend and override transform(Object object) to handle the transformation by yourself.

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");

where original field's name is 'name' but in json ouput it will be replaced with Name.

Sample out:

{"Name":"Abdul Kareem"}


来源:https://stackoverflow.com/questions/7652231/change-property-name-with-flexjson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!