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

本文关键字:分配 属性 对象标识符 json | 更新日期: 2023-09-27 18:24:59

我有一个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.Leether到ColorItemType.Type或ColorItemType.Metal到ColorItemType.Type

而不必创建自定义转换器。

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

试试这个:

  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);
  }