简体   繁体   English

Spring序列,Jackson Json在序列化和反序列化时出现问题

[英]Spring boot, Jackson Json Issue while serializing and deserializing

For some use case, I need to convert one POJO to another POJO with the different fields name. 对于某些用例,我需要将一个POJO转换为另一个具有不同字段名称的POJO。 I tried using Jackson object mapper. 我尝试使用Jackson对象映射器。 It worked in some extends. 它在某种程度上有效。 However end result is not what I expected. 然而最终的结果并不是我的预期。

public class JacksonTest {

    public static void main(String[] args) throws IOException{
        ObjectMapper mapper = new ObjectMapper();
        User user = new User("Deepak", "111", "Singapore");
        UserMap newUser = mapper.convertValue(user, UserMap.class);
        System.out.println("SOUT: " + newUser);
        System.out.println("Jackson: " + mapper.writeValueAsString(newUser));
    }
}

class User {

    User(String name, String id, String address){
        this.name = name;
        this.id = id;
        this.address = address;
    }

    String name;
    String id;
    String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

class UserMap implements Serializable {
    @JsonProperty("name")
    String name;

    private Map<String, Object> meta = new HashMap<>();

    @JsonAnyGetter
    public Map<String, Object> any() {
        return meta;
    }

    @JsonAnySetter
    public void set(String name, Object value) {
        meta.put(name, value);
    }

    @Override
    public String toString() {
        return "UserMap{" +
                "name_new='" + name + '\'' +
                ", meta=" + meta.keySet().stream().map(x-> x+ ":: "+ meta.get(x)).collect(Collectors.joining(", ")) +
                '}';
    }
}

If you run, the output would be : 如果你运行,输出将是:

SOUT: UserMap{name_new='Deepak', meta=address:: Singapore, id:: 111} SOUT:UserMap {name_new ='Deepak',meta = address :: Singapore,id :: 111}

Jackson: {"name":"Deepak","address":"Singapore","id":"111"} Jackson:{“name”:“Deepak”,“address”:“Singapore”,“id”:“111”}

I am using Springboot which internally uses jackson serializer. 我正在使用Springboot,内部使用jackson序列化程序。 It converts the newUser object to normal user class again. 它再次将newUser对象转换为普通用户类。 I want to serialize string in the way class constructed. 我想以类构造的方式序列化字符串。 I want the output in SOUT format. 我想要SOUT格式的输出。

I think you misunderstood what the @JsonAnyGetter/@JsonAnySetter pair will, in effect, do. 我认为你误解了@JsonAnyGetter/@JsonAnySetter对实际上会做什么。

It allows you to create a almost dynamic bean, with mandatory as well as voluntary fields. 它允许您创建一个几乎动态的 bean,包括强制字段和自愿字段。 In your case, the name would be mandatory, and all other fields voluntary. 在您的情况下,名称将是强制性的,所有其他字段是自愿的。

What goes on under the hood is not that your UserMap gets converted to a User . 引擎盖下的内容并不是您的UserMap转换为User What you see is a serialized UserMap, but since it has the same fields and values as the corresponding User instance, their serialized forms look identical. 您看到的是序列化的UserMap,但由于它与相应的User实例具有相同的字段和值,因此它们的序列化表单看起来完全相同。

I couldn't get the auto serialization and deserialization to work using the default Spring boot beans. 我无法使用默认的Spring启动bean使自动序列化和反序列化工作。 In the end, this worked well for me after including Project Lombok and apache BeanUtils: 最后,在包括Project Lombok和apache BeanUtils之后,这对我来说效果很好:

@ToString() @Getter() @Setter() @NoArgsConstructor()
public class User {
    private String email;
    private String bio;
    private String image;
    private String displayName;
    private String userId;
    private long lat;
    private long lng;

    public User(String json) throws JsonParseException, JsonMappingException, IOException, IllegalAccessException, InvocationTargetException {
        ObjectMapper om = new ObjectMapper();
        User u = om.readValue(json, User.class);
        BeanUtils.copyProperties(this, u);
    }
}

http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi https://projectlombok.org/ http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi https://projectlombok.org/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Jackson 对针对 JAVA 类的 JSON 进行序列化和反序列化 - Serializing and deserializing JSON targeting JAVA classes with Jackson 使用Jackson反序列化JSON的问题 - Issue with deserializing JSON using Jackson Spring Boot Kafka 新手关于序列化/反序列化的问题 - Spring Boot Kafka newbie question on serializing / deserializing 使用Jackson进行序列化和反序列化时,处理某些字段的不同类型 - Handle different types for some fields while serializing and deserializing with Jackson 如何在没有注释的情况下使用 Jackson 序列化/反序列化时重命名属性? - How rename property while serializing/deserializing using Jackson without annotations? 为什么在序列化/反序列化几何类型时杰克逊 JSON 映射异常 - Why Jackson JSON mapping exception when Serializing/Deserializing Geometry type 反序列化时,杰克逊api无法识别令牌问题 - unrecognized token issue with jackson api while deserializing 使用Jackson反序列化数组JSON时出错 - Error while deserializing array JSON with Jackson 使用 jackson 反序列化 json 响应时出现 IndexOutOfBoundException - IndexOutOfBoundException while Deserializing a json response using jackson 在 Z2A2D595E6ED9A0B24F0427F2B63B1 中使用 jackson api 时出现 Json 转换错误 - Json conversion error while using jackson api in spring boot miroservice
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM