Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse json string using json.net?

Tags:

json

c#

json.net

I have a string like the following in C#. I tried with JSON.NET but couldn't figure out how to retrieve the value.

"{[{'Name':'AAA','Age':'22','Job':'PPP'},
{'Name':'BBB','Age':'25','Job':'QQQ'},
{'Name':'CCC','Age':'38','Job':'RRR'}]}";

I would like

foreach (user in users){
   Messagebox.show(user.Name,user.Age)
}

Any help will be greatly appreciated.

like image 849
yiqun Avatar asked Mar 06 '13 05:03

yiqun


1 Answers

Here is a code sample:

class Program
{
    static void Main(string[] args)
    {
        var text = @"[{'Name':'AAA','Age':'22','Job':'PPP'},
                    {'Name':'BBB','Age':'25','Job':'QQQ'},
                    {'Name':'CCC','Age':'38','Job':'RRR'}]";

        dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(text);
        for (var i = 0; i < data.Count; i++)
        {
            dynamic item = data[i];
            Console.WriteLine("Name: {0}, Age: {1}", (string)item.Name, (string)item.Age);
        }

        Console.ReadLine();
    }
}

I downloaded Json.Net through NuGet, but otherwise this is a standard .NET 4.0 Console App

like image 71
Glenn Ferrie Avatar answered Sep 21 '22 23:09

Glenn Ferrie