skip to Main Content

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


  1. If you want to use JObjects, you should use JObject result = JObject.Parse(json) instead of dynamic array = JsonConvert.DeserializeObject(json);

    To access the properties of that JObject you would use the syntax var id = result['ID']

    Login or Signup to reply.
  2. you can try this code, if your json object has not nested properties and all properties are primitive

    static void parseItem(string json)
    {
        var item = (JObject)JArray.Parse(json)[0];
        
        foreach (JProperty prop in item.Properties())
        {
            if (prop.Value.Type == JTokenType.Array)
                Console.WriteLine($"{prop.Name}:  {string.Join(",  ", ((JArray)prop.Value))}");
            else Console.WriteLine($"{prop.Name}: {prop.Value}"); ;
        }
    }
    

    or if your properties are more complicated

        var jt = JToken.Parse(json);
        parseItem(jt);
    
    static void parseItem(JToken jt)
    {
        var item = (JObject)jt[0];
        var emails = item["Emails"].ToObject<string[]>();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search