使用动态键 (C#) 解析(反序列化)JSON

Parse (Deserialize) JSON with dynamic keys (C#)

我想解析底部的JSON。直到现在我总是有变量的静态键,但在这个例子中,键总是在变化。这里的“58e7a898dae4c”和“591ab00722c9f”可以有任何值并且不断变化。怎样才能让set的元素值能够达到PreviewName的值?

{
  "key": "gun",
  "objects": [
    {
      "name": "AK47",
      "sets": {
        "58e7a898dae4c": {
          "set_id": "58e75660719a9f513d807c3a",
          "preview": {
            "resource": {
              "preview_name": "preview.040914"
            }
          }
        },
        "591ab00722c9f": {
          "set_id": "58eba618719a9fa36f881403",
          "preview": {
            "resource": {
              "preview_name": "preview.81a54c"
            }
          }
        }
      }
    }
  ]
}
public class Object
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("sets")]
    public Dictionary<string, Set> Sets { get; set; }
}

public class Set
{
    [JsonProperty("set_id")]
    public string SetId { get; set; }

    [JsonProperty("preview")]
    public Preview Preview { get; set; }
}

public class Preview
{
    [JsonProperty("resource")]
    public ResourcePreview Resource { get; set; }
}

public class ResourcePreview
{
    [JsonProperty("preview_name")]
    public string PreviewName { get; set; }
}

var root = JsonConvert.DeserializeObject<RootObject>(json);
string previewName1 = root.Objects[0].Sets["58e7a898dae4c"].Preview.Resource.PreviewName;
string previewName2 = root.Objects[0].Sets["591ab00722c9f"].Preview.Resource.PreviewName;

不需要反序列化,可以解析

var jsonParsed=JObject.Parse(json);

string[] previewNames= ((JArray)jsonParsed["objects"])
.Select(v => ((JObject)v["sets"]))
.Select(i=>i.Properties().Select(y=> y.Value["preview"]["resource"])).First()
.Select(i=> (string) ((JObject)i)["preview_name"]).ToArray();

结果

    preview.040914
    preview.81a54c