0

我正在尝试使用 Genson 将具有 Long id 的对象序列化为 JSON。

如果我序列化为 JSON 并返回到 Java,它会很好地工作。但我在 JavaScript 中反序列化。

JavaScript 不支持完整的 64 位unsigned int作为数字(我发现我的 id 的最后几位在 JavaScript 中被归零),所以我需要在序列化过程中将 Long id 转换为字符串。

我不想转换对象中的所有 Longs,所以我尝试仅将 Converter 用于 id 字段。

import com.owlike.genson.annotation.JsonConverter;
import javax.persistence.Id;
import lombok.Getter;
import lombok.Setter;

...

/** the local database ID for this order */
@JsonConverter(LongToStringConverter.class)
@Id       
@Setter
@Getter
private Long id;

/** The unique ID provided by the client */
@Setter
@Getter
private Long clientKey; 

我的转换器代码如下所示:

public class LongToStringConverter implements Converter<Long> {

    /** Default no-arg constructor required by Genson */
    public LongToStringConverter() {        
    }

    @Override
    public Long deserialize(ObjectReader reader, Context ctx) {
        return reader.valueAsLong();
    }

    @Override
    public void serialize(Long obj, ObjectWriter writer, Context ctx) {
        if (obj != null) {
            writer.writeString(obj.toString());
        }
    }
}

在调用序列化本身时,我没有做任何特别的事情:

    Genson genson = new GensonBuilder().useIndentation(true).create();
    String json = genson.serialize( order );

这行不通。输出仍然如下所示:

{
  "clientKey":9923001278,
  "id":1040012110000000002
}

我想要实现的是:

{
  "clientKey":9923001278,
  "id":"1040012110000000002"   // value is quoted
}

我也尝试将我的 Converter 传递给 GensonBuilder ,但这会命中对象中的所有 Longs,这不是我需要的。

有什么建议吗?

4

1 回答 1

1

好吧,我不清楚为什么,但看起来 Genson 只是没有得到注释。这可能取决于使用 Hibernate 或 Lombok。

解决方案似乎是迫使 Genson 考虑带注释的字段。

我通过使用 GensonBuilder 做到了这一点:

Genson genson = new GensonBuilder().useIndentation(true).include("id").create();
String json = genson.serialize( order );

编辑:结合上面 Eugen 的回答,这也有效,因为它指示 Genson 查看私有字段而不是依赖于 getter/setter:

Genson genson2 = new GensonBuilder().useFields(true, VisibilityFilter.PRIVATE).useMethods(true).create();
于 2019-04-16T02:03:29.230 回答