Anoop Joshi Anoop Joshi - 5 months ago 63
JSON Question

looping through json array in c#

I have a json string like,

{"objectType" : "Subscriber", "objectList":[{"firstName":"name1","email":"email@example.com","address":"exampleAddress"},{"firstName":"name2","email":"email2@example.com","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?

I4V I4V
Answer
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);
}