0

我有一个json字符串如下

{"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]}}

我将其分解为 1 个类,其中 1 个嵌套类让我们调用它们。

    [Serializable]
    public class ColorEntry 
    {
        public int Id { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("base_rgb")]
        [JsonConverter(typeof(JsonColorConverter))]
        public Color BaseRGB { get; set; }

        [JsonProperty("cloth")]
        public ColorItemEntry Cloth { get; set; }

        [JsonProperty("leather")]
        public ColorItemEntry Leather { get; set; }

        [JsonProperty("metal")]
        public ColorItemEntry Metal { get; set; }

        public class ColorItemEntry 
        {
            public ColorItemType Type { get; set; }

            [JsonProperty("brightness")]
            public int Brightness { get; set; }

            [JsonProperty("contrast")]
            public double Contract { get; set; }

            [JsonProperty("hue")]
            public int Hue { get; set; }

            [JsonProperty("saturation")]
            public double Saturation { get; set; }

            [JsonProperty("lightness")]
            public double Lightness { get; set; }

            [JsonProperty("rgb")]
            [JsonConverter(typeof(JsonColorConverter))]
            public Color RGB { get; set; }

        }
    }
    public enum ColorItemType
    {
        Cloth,
        Leather,
        Metal,
    }

我可以将 668 分配给 ColorEntry.ID 并将 ColorItemType.Cloth 分配给 ColorItemType.Type 或 ColorItemType.Leather 分配给 ColorItemType.Type 或 ColorItemType.Metal 分配给 ColorItemType.Type

无需创建自定义转换器。

4

1 回答 1

2

尝试这个:

  dynamic obj = JsonConvert.DeserializeObject(json);      
  foreach (dynamic item in obj as System.Collections.IEnumerable)
  {
    var c = (ColorEntry)obj[item.Name].ToObject(typeof(ColorEntry));
    c.Id = int.Parse(item.Name);
  }
于 2013-07-26T12:24:47.883 回答