Reputation: 65
I'm converting from Newtonsoft.Json to System.Text.Json and I'm faced with data that looks like this:
...
"people": {
"ID001": {
"id": "ID001",
"surame": "Smith",
"given": "Joe"
},
"ID002": {
"id": "ID002",
"surame": "Brown",
"given": "George"
}
},
...
There's an extra, unnecessary, level in there "ID001", "ID002", etc.
Since it's actually data sitting in a spot that should be a label, I'm stuck figuring out how to map it since the "label" is different for every record.
(I will also note that I have no control over the data source; changing it is not an option)
With Newtonsoft, I would read the whole "People" structure into an Perople_Raw object, when would parse by using dynamic I would serialize the individual item, strip off the "IDxxx" value and then reparse the result.
dynamic peopleArray = this.OverallDataObject.People_Raw
foreach (dynamic peopleItem in peopleArray) {
string serialized = JsonConvert.SerializeObject(playerBio_raw);
int posOpenBrace = serialized.IndexOf('{');
Person person = JsonConvert.DeserializeObject<Person>(serialized.Substring(posOpenBrace));
this.OverallDataObject.People.Add(person);
}
System.Text.Json doesn't support that kind of tomfoolery, though, so how can the mapping be specified to end up with an array of Person objects? Through some intermediate object which holds the outer ID plus a Person object?
Upvotes: 2
Views: 540
Reputation: 53650
System.Text.Json supports deserializing to Dictionary<string, TValue>
, so this will work with your data:
public class Container
{
public Dictionary<string, Person> People { get; set; }
}
public class Person
{
public string Id { get; set; }
public string Surame { get; set; }
public string Given { get; set; }
}
Coming from Newtonsoft.Json, it's also important to note that System.Text.Json is case-sensitive by default. Make sure to set PropertyNameCaseInsensitive
:
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};
var deserialized = JsonSerializer.Deserialize<Container>(json, options);
Console.WriteLine(deserialized.People["ID001"].Given); // Joe
Fiddle example: https://dotnetfiddle.net/ipVpdu
Upvotes: 2