在C#中循环遍历json数组 [英] looping through json array in c#

查看:191
本文介绍了在C#中循环遍历json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json字符串,

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"}]}

我需要在我的C#代码中对其进行解析.我已经尝试过了,

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

但是我无法遍历"objectList"数组.怎么做?

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

推荐答案

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

提示:您可以使用此网站将json字符串转换为c#类

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

编辑

使用 Json.Net

dynamic jsonObj = JsonConvert.DeserializeObject(json);

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

这篇关于在C#中循环遍历json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆