1

How to parse data in a List from JSON data like following link using C# ?

{
    "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"
    }]
}
naveen
  • 53,448
  • 46
  • 161
  • 251

2 Answers2

1

try this :

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);
Ali Gh
  • 680
  • 7
  • 9
  • nice answer, but it wont work as the `List` is wrapped inside the `voters` object – naveen Jun 25 '15 at 12:06
  • @naveen you have to use `RootObject` instead of `List`. I've edited the answer to work, waiting for approval... – cramopy Jun 25 '15 at 16:30
0

You are getting an array of objects from the JSON. So all you need is to do a foreach on the voters. JavaScript objects are mapped to Dictionary<string, object> in C#. Pseudo code

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
    }
}
naveen
  • 53,448
  • 46
  • 161
  • 251