Search code examples
c#jsonjson.net

Parsing JSON in C# issue


i have a problem parsing the json, and i hope someone could help.

Here's a JSON response i get from the service

{

    "name":"UPDATE_QUEUE",
    "args":[
        {
            "message":[
                {
                    "service_id":1,
                    "entered":"01:00",
                    "arrival":"01:00"
                },
                {
                    "service_id":2,
                    "entered":"01:00",
                    "arrival":"01:00"
                }
            ]
        }
    ]

}

And here's my Class for the JSON object

    class QueueItem
    {
        public RootObject RootObject { get; set; }
    }


    public class Message
    {
        public int service_id { get; set; }
        public string entered { get; set; }
        public string arrival { get; set; }
    }

    public class Arg
    {
        public List<Message> message { get; set; }
    }

    public class RootObject
    {
        public string name { get; set; }
        public List<Arg> args { get; set; }
    }

And here's my call

QueueItem items
 = JsonConvert.DeserializeObject<QueueItem>(data.MessageText);

I am using Newtonsoft JSON for c# .NET

When i try to call items.RootObject.name i don't get anything, not even trigger for the event ( for example messageBox.Show(items.RootObject.name) ) .


Solution

  • You are deserializing to the wrong type. You should call

    JsonConvert.DeserializeObject<API.jsonObjects.RootObject>(data.MessageText);
    

    The RootObject class matches the JSON which you are deserializing.