将Json字符串转换为Java对象给出null(null)

时间:2018-04-09 13:09:48

标签: java json

你好,我得到了这个Json字符串

{"NexusResource":{"resourceURI":"http://nexus.ad.hrm.se/nexus/service/local/repositories/snapshots/content/se/hrmsoftware/hrm/hrm-release/16.1-SNAPSHOT/","relativePath":"/se/hrmsoftware/hrm/hrm-release/16.1-SNAPSHOT/","text":"16.1-SNAPSHOT","leaf":false,"lastModified":"2018-04-09 12:23:59.0 UTC","sizeOnDisk":-1}}

我想将其转换为名为NexusResource的类的对象,看起来像这个

public class NexusResource {
@JsonProperty("resourceURI") private String resourceURI;
@JsonProperty("relativePath") private String relativePath;
@JsonProperty("text") private String text;
@JsonProperty("leaf") private Boolean leaf;
@JsonProperty("lastModified") private String lastModified;
@JsonProperty("sizeOnDisk") private Integer sizeOnDisk;
@JsonIgnore private Map<String, Object> additionalProperties = new HashMap<>();
}

我尝试使用ObjectMapper转换它

 ObjectMapper mapper = new ObjectMapper();
    NexusResource resource = mapper.readValue(version, NexusResource.class);

版本是Json字符串但是当我记录资源时,我得到的所有内容都是null(null),即使版本获得了所有数据。

3 个答案:

答案 0 :(得分:3)

您可以配置ObjectMapper以解包根值,以便反序列化到您的POJO中。

E.g:

mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);

API

您还可以通过修改POJO来解决这个问题(请参阅Karol的回答)。

如果未选择任何一项,则会导致com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException被抛出,并显示消息:Unrecognized field "NexusResource"

答案 1 :(得分:1)

NGINX不是JSON的根,而是密钥。要使Java映射工作,您应该定义包装类型:

NexusResource

然后用它来映射:

public class NexusResources {
  @JsonProperty("NexusResource") private NexusResource root;
  ...
}

答案 2 :(得分:1)

问题是JSON与您尝试解析的类不匹配。请注意,JSON有一个名为&#34; NexusResource&#34;的字段。拥有所有其他领域。而NexusResource.class类只有字段。你可以做两件事。更改JSON以匹配NexusResource.class,或创建一个与JSON匹配的新类。

1)将json更改为以下内容。

{"resourceURI":"http://nexus.ad.hrm.se/nexus/service/local/repositories/snapshots/content/se/hrmsoftware/hrm/hrm-release/16.1-SNAPSHOT/","relativePath":"/se/hrmsoftware/hrm/hrm-release/16.1-SNAPSHOT/","text":"16.1-SNAPSHOT","leaf":false,"lastModified":"2018-04-09 12:23:59.0 UTC","sizeOnDisk":-1}

2)创建一个与你的Json实际匹配的新类。

class NexusResourceJson {

    @JsonProperty("NexusResource ")
    NexusResource resource;

    public NexusResource getResource() {return resource;}
}


ObjectMapper mapper = new ObjectMapper();
NexusResource resource = mapper.readValue(version, NexusResourceJson.class).getResource();