如何使用C#从JSON数据解析List中的数据,如下面的链接?

时间:2015-06-25 10:36:08

标签: c# asp.net json

如何使用C#解析JSON数据中的数据,例如关注link

{
    "voters": [{
        "id": "5644309456813",
        "name": "Rimi Khanom",
        "address": "House no: 12. Road no: 14. Dhanmondi, Dhaka",
        "date_of_birth": "1979-01-15"
    }, {
        "id": "9509623450915",
        "name": "Asif Latif",
        "address": "House no: 98. Road no: 14. Katalgonj, Chittagong",
        "date_of_birth": "1988-07-11"
    }, {
        "id": "1098789543218",
        "name": "Rakib Hasan",
        "address": "Vill. Shantinagar. Thana: Katalgonj, Faridpur",
        "date_of_birth": "1982-04-12"
    }, {
        "id": "7865409458659",
        "name": "Rumon Sarker",
        "address": "Kishorginj",
        "date_of_birth": "1970-12-02"
    }, {
        "id": "8909854343334",
        "name": "Gaji Salah Uddin",
        "address": "Chittagong",
        "date_of_birth": "1965-06-16"
    }]
}

2 个答案:

答案 0 :(得分:1)

试试这个:

public class Voter
{
    public string id { get; set; }
    public string name { get; set; }
    public string address { get; set; }
    public string date_of_birth { get; set; }
}

public class RootObject
{
    public List<Voter> voters { get; set; }
}

var VoterModel = JsonConvert.DeserializeObject<List<Voter>>(json);

答案 1 :(得分:0)

您正在从JSON获取一组对象。所以你需要的是对选民做foreach。 JavaScript对象在C#中映射到Dictionary<string, object>。伪代码

using System.Web.Script.Serialization;
using System.Net;

using (var client = new WebClient())
{
    var url = "http://nerdcastlebd.com/web_service/voterdb/index.php/voters/all/format/json";
    var jsonString = client.DownloadString(url);
    var json = new JavaScriptSerializer().Deserialize<dynamic>(jsonString);
    foreach (Dictionary<string, object> voter in json["voters"])
    {
        var id = voter["id"].ToString();
        // pull name, address and date_of_birth here
    }
}