Home > Net >  Reading JSON file that is an array in C# with unknown keys
Reading JSON file that is an array in C# with unknown keys

Time:01-21

I am having trouble reading from this JSON file:

[
  {
    "id":"100",
    "name": "myname",
    "playlists": {
       "unknown key": ["song 1", "song2"]
    }
  }
]

here is my guild class:

public class Guild{
  public string id = "";
  public string name = "";
  public Dictionary<string, List<string>> playlists;
  

  public Guild(string name, string id, Dictionary<string, List<string>> playlists){
    this.name = name;
    this.id = id;
    this.playlists = playlists;
  }
}

Im having trouble reading from this JSON file because of the unknown keys and the array that surrounds the entire JSON file. Can someone please help? What am I doing wrong?

CodePudding user response:

You're using fields. Traditionally you should use properties:

public class Guild {
  public string Id { get; set; }
  public string Name { get; set; }
  public Dictionary<string, List<string>> playlists { get; set; }
}

But the primary problem is that you need to deserialize into a List<Guild> or Guild[] since the input JSON is an array of Guild.

var guilds = JsonConvert.DeserializeObject<List<Guild>>(inputJson);

CodePudding user response:

If you're using .NET 6, you could directly use JsonArray from System.Text.Json.Nodes. For instance, to get first unknown key:

using System.Text.Json;
using System.Text.Json.Nodes;

var json_string = @"
[
  {
    ""id"":""100"",
    ""name"": ""myname"",
    ""playlists"": {
      ""unknown key"": [""song 1"", ""song2""]
    }
  }
]
";

var guild = JsonSerializer.SerializeToNode(JsonNode.Parse(json_string)) as JsonArray;
var firstUnknownKey = guild[0]["playlists"]["unknown key"][0];
WriteLine(firstUnknownKey); // Prints: song 1
  •  Tags:  
  • Related