Reputation: 2531
I have a json string as follows
{"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]}}
I break this down into 1 Class with 1 nested class lets call them.
[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,
}
Can I assign the 668 to ColorEntry.ID and ColorItemType.Cloth to ColorItemType.Type or ColorItemType.Leather to ColorItemType.Type or ColorItemType.Metal to ColorItemType.Type
without having to create a custom converter.
Upvotes: 0
Views: 398
Reputation: 1881
try this:
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);
}
Upvotes: 2