如何使用json属性将json映射到java对象

时间:2016-06-06 20:23:42

标签: java json jackson gson

我无法在java对象中映射这个json。问题是我无法将值v0.1.0映射到我的java对象可以任何人帮我如何将这个json映射到java对象。我不是用v0.1.0声明可变名称所以我使用json属性注释。但这不适合我。

如何从这个json创建java对象:

{
    "availableVariants": {
        "v0.1.0": {
            "resourceName": "raja",
            "get": "www.google.com",
            "deltaGet": "",
            "post": null,
            "put": null,
            "delete": null
        },
        "v1.1.0": {
            "resourceName": "raja",
            "get": "www.google.com",
            "deltaGet": "",
            "post": null,
            "put": null,
            "delete": null
        }
    }
}

I am not able to make java object for this json .

1 个答案:

答案 0 :(得分:0)

如果你想到" v0.1.0"问题会变得更简单吗?和" v1.1.0"作为地图中的键而不是对象的属性?尝试这样的事情:

public class Resource {
    private String resourceName;
    private String get;
    private String deltaGet;
    private String post;
    private String put;
    private String delete;

    // public getters and setters
}

public class VariantInfo {
    // resources indexed by version
    private Map<String, Resource> availableVariants; 
    // public getter and setter
}

public VariantInfo parseVariants(String json) {
    ObjectMapper objectMapper = (wherever your Jackson object mapper comes from);
    return objectMapper.readValue(json, VariantInfo.class);
}