java 使用Jackson将包含空值Map的Json对象反序列化为Immutable

gfttwv5a  于 2023-08-01  发布在  Java
关注(0)|答案(2)|浏览(139)

我尝试反序列化包含以下结构的Json对象,但在反序列化过程中收到Jackson的错误,原因是包含Json对象的map中出现了null值。有没有一种方法可以反序列化这些值,并将它们作为null或空字符串放入Map中?

{
    "id": "1"
    "links: {
          "a": "someLink"
          "b": null
          ....
     }
}

字符串
我用以下方式创建了一个不可变的:

@Value.Immutable
@JsonSerialize(as = ImmutableMyClass.class)
@JsonDeserialize(as = ImmutableMyClass.class)
public interface MyClass {

    @JsonProperty("id")
    String getId();

    @JsonProperty("links")
    Map<String, String> getLinks();
}


我将对象读入Java POJO如下:

List<MyClass> myClassList = objectMapper.readValue(jsonString, objectMapper.getTypeFactory.constructCollectionType(List.class, ImmutableMyClass.class))


错误代码:

com.fasterxml.jackson.databind.exc.ValueInstantiationException problem: null value in entry: b=null

nhn9ugyo

nhn9ugyo1#

也许可以尝试类似这样的东西(通过接口使用@Value.Immutable

@JsonProperty("links")
Map<String, Optional<String>> getLinks();

@Value.Lazy
Map<String, String> getLinksValues() {
    return getLinks().entrySet().collect(Map.Entry::getKey, e -> e.getValue().orElse(null)));
}

字符串
或(不含@Value.Immutable

private final Map<String, String> links;

setLinks(Map<String, String> links) {
    this.links = links;
}

Map<String, String> getLinks() {
    return links;
}

ttcibm8c

ttcibm8c2#

我刚刚用Jackson2.15.2版测试了你的测试用例,它工作得很好。我没有使用Immutable注解,也没有使用@JsonSerialize@JsonDeserialize注解。下面是我的代码和输出:
classMapHolder

package com.mgnt.stam;

import java.util.Map;

public class MapHolder {
    private Integer id;
    private Map<String, Object> address;

    public Integer getId() {
        return id;
    }

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

    public Map<String, Object> getAddress() {
        return address;
    }

    public void setAddress(Map<String, Object> address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "MapHolder{" +
                "id=" + id +
                ", address=" + address +
                '}';
    }

字符串
}
我的代码:

try{        
        MapHolder mapHolder = JsonUtils.readObjectFromJsonString("{\"id\": 1,\"address\": {\"city\": \"Mountain View\",\"state\": \"CA\",\"zipcode\": 94041, \"appt\": null}}", MapHolder.class);
        System.out.println(mapHolder);
    } catch (IOException e) {
        ...;
    }


输出:

MapHolder{id=1, address={city=Mountain View, state=CA, zipcode=94041, appt=null}}


澄清:class JsonUtils来自我编写和维护的MgntUtils开源库。该类是Jacksonv 2.15.2中ObjectMapper类的一个精简 Package 器。这是一个Javadoc for JsonUtils。该库可以作为Maven artifact from Maven Central或从GitHub获得(包括源代码和Javadoc)

相关问题