我有一个json字符串,

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

我需要在我的C#代码中解析它。我试过了,
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
object routes_list = json_serializer.DeserializeObject(myjson here);

但是我无法遍历“objectList”数组。怎么做?

最佳答案

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; }
}

提示:您可以使用this site将json字符串转换为C#类

编辑

使用Json.Net
dynamic jsonObj = JsonConvert.DeserializeObject(json);

foreach (var obj in jsonObj.objectList)
{
    Console.WriteLine(obj.address);
}

07-24 03:14