-1

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;
A9191
  • 23
  • 5
  • why you made `preview` and `resource` dictionary ? they have only 1 property `resource` and `preview_name` respectively – Selvin Apr 27 '22 at 14:05
  • What is your problem exactly? You have declared `Sets` as `public Dictionary Sets { get; set; }` which is the correct way to deserialize a JSON object with unknown keys. As far as I can see your code looks good, so where are you stuck? – dbc Apr 27 '22 at 15:48
  • @dbc Thanks for your comment, I was not sure if I did everything properly or not. When I want to get the `root.Objects[0].Sets` it gives me `System.Collections.Generic.Dictionary`2[System.String,Set]` – A9191 Apr 27 '22 at 16:19
  • 1
    Then do you just need [How to iterate over a dictionary?](https://stackoverflow.com/q/141088/3744182)? – dbc Apr 27 '22 at 16:24

1 Answers1

1

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
Serge
  • 40,935
  • 4
  • 18
  • 45