如何将json对象标识符分配给属性

时间:2013-07-26 12:00:09

标签: c# .net json json.net

我有一个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 to ColorItemType.Type

无需创建自定义转换器。

1 个答案:

答案 0 :(得分: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);
  }