C# Json反序列化

0x00.使用工具将Json格式化

Json作为一种数据交换格式,具有简洁和清晰的结构。
在线Json格式化校验工具:http://tool.chinaz.com/tools/jsonformat.aspx

在线转换C#类工具:http://json2csharp.chahuo.com/

Json数据
{
    "code": "00",
    "count": 1,
    "followersList": [
        {
            "followerDate": "2017-11-29 11:11:10",
            "follower_id": "WEP2DU",
            "userIconPath": "http://www.sonystyle.com.cn/mysony/acafe/myspace/images/space/default.gif"
        }
    ],
    "programId": 1,
    "userId": "YIOMOOOO"
}
使用C#类工具转换后新建一个”JsonFollower”类
class JsonFollower
{
    public class FollowersList
    {
        public string followerDate { get; set; }
        public string follower_id { get; set; }
        public string userIconPath { get; set; }
    }

    public class RootObject
    {
        public string code { get; set; }
        public string count { get; set; }
        public List<followerslist> followersList { get; set; }
        public List<followering> following { get; set; }
        public string programId { get; set; }
        public string userId { get; set; }
    }
}

0x01.添加引用

using System.Collections.Generic;
using System.Net.Http;
using Newtonsoft.Json;//在Nuget中下载对应类库

0x02.模拟发送请求获取Json

HttpClient request = new HttpClient();
HttpResponseMessage MyFolResponse = request.GetAsync("http://www.sonystyle.com.cn/mysony/campaign/api/program.do?methodName=getMyFollowersList&programId=1" + "&userId=YIOMOOOO").Result;
string a = MyFolResponse.Content.ReadAsStringAsync().Result;
JsonFollower.RootObject rb1 = JsonConvert.DeserializeObject<JsonFollower.RootObject>(a);

0x03.遍历RootObject并转化为对象

List<FollowerInfo> FolInfo = new List<FollowerInfo >();
List<string> followerDate = new List<string>();
List<string> follower_id = new List<string>();

foreach (JsonFollower.FollowersList fl in rb1.followersList)
{
    followerDate.Add(fl.followerDate);
    follower_id.Add(fl.follower_id);
}

for (int i = 0; i < follower_id.Count; i++)
{
    FollowerInfo FI = new FollowerInfo();
    FI.followerDate = followerDate[i];
    FI.follower_id = follower_id[i];
    FolInfo.Add(FI);
}
return FolInfo;