我有一个像这样的 json 字符串,
{"objectType" : "Subscriber", "objectList":[{"firstName":"name1","email":"email@example.com","address":"exampleAddress"},{"firstName":"name2","email":"email2@example.com","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);
}
关于c# - 在 C# 中循环遍历 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16646451/