Json 到 pojo 的转换 [英] Json to pojo convertions

查看:35
本文介绍了Json 到 pojo 的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何将以下类型的 json 转换为 java 对象

How we convert following type of json into java object

{
    "complaint_Map": {
        "1000067730": "3011351597604397",
        "1000067730-06": "10582576134561065"
    }
}

如果有人对此有任何想法,请告诉我们如何做到这一点.

if anyone have any idea about this tell how we do that.

推荐答案

如果您想要使用 Jackson 库的解决方案,这里是.

If you want a solution using Jackson library, here it is.

自定义类:

@JsonRootName("complaint_Map")
public class Complaint {
    private String firstKey;
    private String secondKey;

    @JsonProperty("1000067730")
    public String getFirstKey() {
        return firstKey;
    }
    @JsonProperty("1000067730")
    public void setFirstKey(String firstKey) {
        this.firstKey = firstKey;
    }

    @JsonProperty("1000067730-06")
    public String getSecondKey() {
        return secondKey;
    }

    @JsonProperty("1000067730-06")
    public void setSecondKey(String secondKey) {
        this.secondKey = secondKey;
    }

    @Override
    public String toString() {
        return "Complaint{" +
                "firstKey='" + firstKey + '\'' +
                ", secondKey='" + secondKey + '\'' +
                '}';
    }
}

以及测试方式:

String jsonString = "{\"complaint_Map\":{\"1000067730\":\"3011351597604397\",\"1000067730-06\":\"10582576134561065\"}}";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
try {
    Complaint complaint = mapper.readValue(jsonString, Complaint.class);
    System.out.println(complaint);
} catch (Exception e) {
    e.printStackTrace();
}

我使用了以下版本(在 Maven pom 中):

I used the following version (in Maven pom):

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.1.3</version>
</dependency>

这篇关于Json 到 pojo 的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆