0

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

映射器类是:

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 出现在字段的位置。我怎么做。有什么帮助吗?

4

3 回答 3

0
private T field;

将以上内容更改为:

private T name;
于 2013-05-14T10:56:32.880 回答
0

我认为你问的不是 JSON 的默认行为。字段名是 json 映射的“键”,而不是变量名。你应该重命名该字段或进行一些字符串过程来完成它。

于 2013-05-14T10:37:03.973 回答
0

您需要一个自定义序列化程序来做到这一点。这是一个运行时数据转换,Jackson 除了使用自定义序列化程序之外不支持数据转换(嗯,有值的包装/解包,但我们不要去那里)。此外,您需要提前知道要在序列化程序中应用的每种类型的转换。以下作品:

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();
    }
}
于 2013-05-14T14:28:49.663 回答