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?
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);
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.