c# - 在 C# 中循环遍历 json 数组

标签 c# json parsing

我有一个像这样的 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/

相关文章:

JavaScript从json获取数据到全局变量

parsing - 为什么我的递归 FParsec 解析器在解析嵌套数组时会抛出异常?

python - 如何使用 BeautifulSoup (python) 防止关闭错误 HTML 中的标签?

c# - Visual Studio 2010 表达错误 "Requested registry access is not allowed"

php - 如何将两个具有不同类型实体的数组组合成一个 json 对象?

c# mysql 等待上一个查询完成

android - 使用 JSON 从平板电脑本地文件加载图像

c# - 查找句子的更简单方法是大字符串?

c# - 如何获取具有特定名称的所有节点

c# - 在 .NET 的 Python 中实现 C# 接口(interface)