将java对象的通用字段序列化为json

时间:2013-05-14 10:30:31

标签: java json jackson

我在User.java中有一个通用字段。我想在json中使用T的值。

public class User<T> {

public enum Gender {MALE, FEMALE};


private T field;
private Gender _gender;
private boolean _isVerified;
private byte[] _userImage;

public T getField() { return field; }
public boolean isVerified() { return _isVerified; }
public Gender getGender() { return _gender; }
public byte[] getUserImage() { return _userImage; }

public void setField(T f) { field = f; }
public void setVerified(boolean b) { _isVerified = b; }
public void setGender(Gender g) { _gender = g; }
public void setUserImage(byte[] b) { _userImage = b; }
}

和mapper类是:

public class App 
{
public static void main( String[] args ) throws JsonParseException, JsonMappingException, IOException
{
    ObjectMapper mapper = new ObjectMapper();
    Name n = new Name();
    n.setFirst("Harry");
    n.setLast("Potter");
    User<Name> user = new User<Name>();
    user.setField(n);
    user.setGender(Gender.MALE);
    user.setVerified(false);

    mapper.writeValue(new File("user1.json"), user);
}
}

并且json输出为:

{"field":{"first":"Harry","last":"Potter"},"gender":"MALE","verified":false,"userImage":null}

在输出中,我希望Name出现在字段的位置。我怎么做。有什么帮助吗?

3 个答案:

答案 0 :(得分:0)

我认为你问的不是JSON的默认行为。字段名称是json映射的“键”,而不是变量名称。你应该重命名字段或者做一些String处理来做它。

答案 1 :(得分:0)

private T field;

将上述内容更改为:

private T name;

答案 2 :(得分:0)

您需要自定义序列化程序才能执行此操作。这是一个运行时数据转换,杰克逊除了使用自定义序列化器之外不支持数据转换(好吧,有包装/展开值,但是不要去那里)。此外,您需要事先知道要在序列化程序中应用的每种类型的转换。以下作品:

public class UserSerializer extends JsonSerializer<User<?>> {
    private static final String USER_IMAGE_FIELD = "userImage";
    private static final String VERIFIED_FIELD = "verified";
    private static final String FIELD_FIELD = "field";
    private static final String NAME_FIELD = "name";
    @Override
    public void serialize(User<?> value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jgen.writeStartObject();
        if (value.field instanceof Name) {
            jgen.writeFieldName(NAME_FIELD);
        } else {
            jgen.writeFieldName(FIELD_FIELD);
        }
        jgen.writeObject(value.field);
        jgen.writeStringField("gender", value._gender.name());
        jgen.writeBooleanField(VERIFIED_FIELD, value._isVerified);
        if (value._userImage == null) {
            jgen.writeNullField(USER_IMAGE_FIELD);
        } else {
            jgen.writeBinaryField(USER_IMAGE_FIELD, value._userImage);
        }
        jgen.writeEndObject();
    }
}