Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping through json array in c#

Tags:

json

c#

parsing

I have a json string like,

{"objectType" : "Subscriber", "objectList":[{"firstName":"name1","email":"[email protected]","address":"exampleAddress"},{"firstName":"name2","email":"[email protected]","address":"exampleAddress2"}]}

I need to parse it in my C# code. I have tried,

JavaScriptSerializer json_serializer = new JavaScriptSerializer();
object routes_list = json_serializer.DeserializeObject(myjson here);

But i cant loop through the "objectList" array. How it can be done?

like image 807
Anoop Joshi P Avatar asked May 20 '13 09:05

Anoop Joshi P


2 Answers

var jsonObj = new JavaScriptSerializer().Deserialize<RootObj>(json);
foreach (var obj in jsonObj.objectList)
{
    Console.WriteLine(obj.address);
}


public class ObjectList
{
    public string firstName { get; set; }
    public string email { get; set; }
    public string address { get; set; }
}

public class RootObj
{
    public string objectType { get; set; }
    public List<ObjectList> objectList { get; set; }
}

Hint: You can use this site to convert your json string to c# classes

EDIT

using Json.Net

dynamic jsonObj = JsonConvert.DeserializeObject(json);

foreach (var obj in jsonObj.objectList)
{
    Console.WriteLine(obj.address);
}
like image 104
I4V Avatar answered Nov 20 '22 02:11

I4V


var routes_list = (Dictionary<string, object>)json_serializer.DeserializeObject(myjson);

foreach (var record in routes_list)
{
    Console.WriteLine(record);
}
like image 4
paramosh Avatar answered Nov 20 '22 00:11

paramosh