Reputation: 1
I want to get the "fruits","animals","numbers" from a JSON using c# and also I want to get the values inside the "fruits", "animals" and "numbers" I'm using the json.net but I can't be figured out how I can get the data I want.
{
"fruits":[
"apple",
"orange",
"grapes",
"banana"
],
"animals":[
"cat",
"dog",
"lion",
"bird",
"horse"
],
"numbers":[
"1",
"2",
"3",
"4",
"5"
]
}
I know I can achieve this by having this
public class RootObject
{
public List<string> fruits { get; set; }
public List<string> animals { get; set; }
public List<string> numbers { get; set; }
}
but when I add another object like colors so I need to add
public List<string> colors{ get; set; }
what I want is just simply get the object name and its values without having to define a new property.
I know this was already answered if ever please just comment some links.
Upvotes: 0
Views: 151
Reputation: 738
You can use a generic dictionary for your type and deserialize with the Newtonsoft JSON library. Assuming your JSON sample is in the file C:\temp\json.txt:
string json = File.ReadAllText(@"C:\Temp\json.txt");
var stuff = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(json);
then you can get your fruits or colors or whatever out of the dictionary.
Upvotes: 1
Reputation: 1796
You are right, you can not make use of classes while parsing the given JSON
because your JSON
data is not fixed and not related to the specific items, that's why its the place where you can make use of dynamic
object within a dictionary.
The following example demonstrates how you can make it work. I've added 2 more items i.e. cars and laptops
string json = "{'fruits':['apple','orange','grapes','banana']," +
"'animals':['cat','dog','lion','bird','horse' ]," +
"'cars':['bmw','mustang','suzuki']," +
"'laptops':['hp','acer','samsung','microsoft','mac' ]," +
"'numbers':['1','2','3','4','5' ]}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json);
foreach (var item in dict)
{
var objName = item.Key;
var items = item.Value;
}
Here is the execution of the above code. Hope it helps.
Upvotes: 0