如何用gson解析这个问题

时间:2013-09-06 15:20:42

标签: java nested gson

这是json数据(我无法控制)

{
"colors": {
    "668": {
        "name": "Pink Ice",
        "base_rgb": [
            128,
            26,
            26
        ],
        "cloth": {
            "brightness": 50,
            "contrast": 1.36719,
            "hue": 8,
            "saturation": 0.351563,
            "lightness": 1.36719,
            "rgb": [
                216,
                172,
                164
            ]
        },
        "leather": {
            "brightness": 47,
            "contrast": 1.71875,
            "hue": 8,
            "saturation": 0.234375,
            "lightness": 1.71875,
            "rgb": [
                207,
                170,
                163
            ]
        },
        "metal": {
            "brightness": 47,
            "contrast": 1.64063,
            "hue": 8,
            "saturation": 0.429688,
            "lightness": 1.48438,
            "rgb": [
                211,
                145,
                134
            ]
        }
    }
},
"657": {
    "name": "Pastel Pink",
    "base_rgb": [
        128,
        26,
        26
    ],
    "cloth": {
        "brightness": 52,
        "contrast": 1.40625,
        "hue": 8,
        "saturation": 0.585938,
        "lightness": 1.40625,
        "rgb": [
            247,
            170,
            157
        ]
    },
    "leather": {
        "brightness": 52,
        "contrast": 1.40625,
        "hue": 8,
        "saturation": 0.546875,
        "lightness": 1.40625,
        "rgb": [
            243,
            172,
            159
        ]
    },
    "metal": {
        "brightness": 47,
        "contrast": 1.5625,
        "hue": 8,
        "saturation": 0.546875,
        "lightness": 1.40625,
        "rgb": [
            220,
            141,
            126
        ]
    }
}

}

我不能为我的生活弄清楚如何构建存储它的类。 “668”(身份证号码)是我的绊脚石。

我知道在没有展示我尝试的不是好形式的情况下寻求帮助,但是我尝试过的任何东西都没有接近,而且只会占用大量空间而无处可去。

1 个答案:

答案 0 :(得分:2)

您的类层次结构将具有以下骨架

public class Holder {
    private Colors colors;
}

public class Colors {
    private Map<String, Item> map;
}

public class Item {
    private String name;
    private int[] base_rgb;
    private Cloth cloth;
    ... // more
}

public class Cloth {
    private int brightness;
    private float contrast;
    private int hue;
    private float saturation;
    private float lightness;
    private int[] rgb;
}

您需要MetalLeather以及其他人的课程。

上面的类Holder将是序列化到您发布的JSON的类。如果您不想为base_rgb(不遵循惯例)等字段命名,则可以使用@JsonProperty(非Gson)等库特定注释和name属性来提供它们是一个JSON名称,并根据您的需要为该字段命名。

Gson还提供了JsonSerializerJsonDeserializer来真正自定义序列化/反序列化。