JSON动态属性名称

时间:2019-12-07 15:48:42

标签: c# json json.net

我有一个如下的json数据,具有相同的Image结构和不同的颜色名称。

     {    
      "colorImages":{
    "Giraffe-safari Sand": [
      {
        "large": "...jpg",
        "thumb": "...jpg",
        "hiRes": "...jpg",        
        "main": {
          "...jpg": [ "862", "679" ],
          "...jpg": [ "434", "342" ],
          "...jpg": [ "663", "522" ]         
        }
      },
      {
        "large": "...jpg",
        "thumb": "...jpg",
        "hiRes": "...jpg",       
        "main": {
          "...jpg": [ "606", "398" ],
          "...jpg": [ "500", "328" ]          
        }
      }],
      "Pawprint - Burgundy": [
      {
        "large": "...jpg",
        "thumb": "...jpg",
        "hiRes": "...jpg",        
        "main": {
          "...jpg": [ "862", "679" ],
          "...jpg": [ "434", "342" ],
          "...jpg": [ "663", "522" ]         
        }
      },
      {
        "large": "...jpg",
        "thumb": "...jpg",
        "hiRes": "...jpg",       
        "main": {
          "...jpg": [ "606", "398" ],
          "...jpg": [ "500", "328" ]          
        }
      }]
  }
}

我的模型班:

public partial class Aa
{
    [JsonProperty("colorImages")]
    public Images ColorImages { get; set; }
}

public partial class Images
{
   [JsonProperty("Giraffe-safari Sand")]
    public List<ImageItem> GiraffeSafariSand { get; set; }

    [JsonProperty("Pawprint - Burgundy")]
    public List<ImageItem> PawprintBurgundy { get; set; }
}
public partial class ImageItem
    {
        [JsonProperty("large")]
        public Uri Large { get; set; }

        [JsonProperty("thumb")]
        public Uri Thumb { get; set; }

        [JsonProperty("hiRes")]
        public Uri HiRes { get; set; }

        [JsonProperty("variant")]
        public string Variant { get; set; }

        [JsonProperty("main")]
        public Dictionary<string, List<long>> Main { get; set; }
    }

如何使用Jsonconverter作为动态属性名称,这样我就不需要重复[JsonProperty(“ Giraffe-safari Sand”)]和[JsonProperty(“ Pawprint-Burgundy”)],因为会有成千上万的颜色名称处理。

2 个答案:

答案 0 :(得分:0)

要创建自定义的动态商品名称和值,可以使用字典:

[JsonProperty("Images")]
public Dictionary<string, List<ImageItem>> Images { get; set; }

答案 1 :(得分:0)

您可以使用JSonConvert中的Microsoft.Json方法。像这样编辑对象。

public class Aa
    {
        [JsonProperty("colorImages")]
        public Dictionary<string, List<ImageItem>> Images { get; set; }
    }
    public class ImageItem
    {
        [JsonProperty("large")]
        public Uri Large { get; set; }

        [JsonProperty("thumb")]
        public Uri Thumb { get; set; }

        [JsonProperty("hiRes")]
        public Uri HiRes { get; set; }

        [JsonProperty("variant")]
        public string Variant { get; set; }

        [JsonProperty("main")]
        public Dictionary<string, List<long>> Main { get; set; }
    }

在您的转换代码中:

var deserializedSrc = JsonConvert.DeserializeObject<Aa>(src);

您将拥有一个字典,其中的键将为Giraffe-safari SandPawprint - Burgundy等。