I want to convert JSON to object. The code below works fine.
internal class Program
{
static void Main(string[] args)
{
string json = @"{
'name': 'Ayrton Senna',
'friends': [
{
'name': 'John',
'age': 34
},
{
'name': 'Jack',
'age': 32
}
]
}";
var person = JsonConvert.DeserializeObject<Person>(json);
}
public class Person
{
public string Name { get; set; }
public List<Friend> Friends { get; set; }
public class Friend
{
public string Name { get; set; }
public int Age { get; set; }
}
}
}
However in the Person Class I want the property List to be dictionary. The key will be string that should be "friends" (somehow taken from the Json and not hardcoded). The value will be list of objects.
Example:
public class Person
{
public string Name { get; set; }
public Dictionary<string, List<Friend>> Friends { get; set; }
public class Friend
{
public string Name { get; set; }
public int Age { get; set; }
}
}
The reason I want this is so when i will have different JSON for example:
{
"id": 1,
"name": "Ayrton Senna",
"mates": [
{
"name": "John",
"age": 12
},
{
"name": "Jack",
"age": 32
}
]
}
Another example Json:
{
"id": 1,
"name": "Ayrton Senna",
"companions": [
{
"name": "John",
"age": 12
},
{
"name": "Jack",
"age": 32
}
]
}
I need to capture/store the name of the list like: "friends", "mates", "companions" because i will need to display them later. I will have 20 Json files like this and only this property name will be different. So i need to read ir from the json and store it somehow.
I want a class that will be more "generic".
Is this even doable? If you have some other suggestions please do tell. Any help will be much appreciated!