【问题标题】:FlexJSON change property name - on Date fieldsFlexJSON 更改属性名称 - 在日期字段上
【发布时间】:2012-07-05 01:01:55
【问题描述】:

我从这里找到了这段代码: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 失败:尝试深度序列化时出错

当我注释掉 transform new Field... 行时它工作正常,当我尝试更改类型字段时它工作正常,它是一个字符串。

尝试修改和 Int 时它也会失败,我希望其他所有内容都不是字符串。

如果有人熟悉 FlexJSON API 并能在此处为我指明正确的方向,我将不胜感激。

【问题讨论】:

    标签: java json flexjson


    【解决方案1】:

    您只需要更改这部分代码:

    getContext().writeQuoted((String) object);
    

    对于大多数类型,如果您将其更改为:

    getContext().writeQuoted(object.toString());
    

    如果这不适用于 Date 值 - 只需像这样重写集成 SimpleDateFormat:

    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    getContext().writeQuoted(sdf.format(object));
    

    这应该可以解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-25
      • 2016-06-24
      • 2020-01-27
      • 2012-01-18
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多