I am writing a JsonParser in C# (using a reference from SO). This might be a simple question, but I am new to C#, and thanks for your help.
I am wondering if a JObject
can be passed to another function for JSON parsing.
using (StreamReader r = new StreamReader("Input.json"))
{
string json = r.ReadToEnd();
dynamic array = JsonConvert.DeserializeObject(json);
foreach(var item in array)
{
Console.WriteLine("Item Type: {0}", item.GetType());
Console.WriteLine("ID: {0}", item.ID);
Console.WriteLine("Name: {0}", item.Name);
Console.WriteLine("Age: {0}", item.Age);
}
}
I want to do the JSON parsing in a dynamic approach without creating a POJO. Can I pass the item
to a function that takes care of the parsing? What will the object type be that I could pass here?
static void parseJson() {
using (StreamReader r = new StreamReader("Input.json"))
{
string json = r.ReadToEnd();
dynamic array = JsonConvert.DeserializeObject(json);
foreach(var item in array)
{
Console.WriteLine("Item Type: {0}", item.GetType());
parseItem(item);
}
}
}
static void parseItem(JObject item) {
Console.WriteLine("ID: {0}", item.ID);
Console.WriteLine("Name: {0}", item.Name);
Console.WriteLine("Age: {0}", item.Age);
}
Say my Json file is something like this.
[
{
"ID": "1",
"Name": "abc"
"Age": "1"
"Emails": [
"[email protected]",
"[email protected]",
"[email protected]",
]
}
]
2
Answers
If you want to use JObjects, you should use
JObject result = JObject.Parse(json)
instead ofdynamic array = JsonConvert.DeserializeObject(json);
To access the properties of that JObject you would use the syntax
var id = result['ID']
you can try this code, if your json object has not nested properties and all properties are primitive
or if your properties are more complicated