Home > Net >  Parse (Deserialize) JSON with dynamic keys (C#)
Parse (Deserialize) JSON with dynamic keys (C#)

Time:04-28

I want to parse the JSON on the bottom. Till now I always have the static key for the variables, but in this example, the keys are always changing. Here the "58e7a898dae4c" and "591ab00722c9f" could have any value and change constantly. How can I get the value of the elements of the set to be able to reach the PreviewName value?

{
  "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;

CodePudding user response:

you don't need to deserialize, you can parse

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

result

    preview.040914
    preview.81a54c
  • Related