Jonathan Small
Jonathan Small

Reputation: 1079

C# ASP.NET MVC convert string to list using JSON

I have an application where I am receiving a datafeed. The data looks like this after the code below is executed, the variable 'result' looks like this:

[
    { 
        "personName": "Avery Davis",
        "personOrganization": "01"
    },
    {
        "personName": "Chris Davis",
        "personOrganization": "01"
    },
    {
        "personName": "Tony Davis",
        "personOrganization": "01"
    },
    {
        "personName": "Cory Dirt",
        "personOrganization": "01"
    },
    {
        "personName": "Tyler Dirt",
        "personOrganization": "01"
    },
    {
        "personName": "Ann Ford",
        "personOrganization": "01"
    },
    {
        "personName": "Lauren Ford",
        "personOrganization": "01"
    },
    {
        "personName": "Lauren Ford",
        "personOrganization": "01"
    },
    {
        "personName": "Avery Franklin",
        "personOrganization": "01"
    }
]

I have a model class which looks like this:

public class AllPeople
{
    public List<PeopleList> data { get; set; }
}

public class PeopleList
{
    public string personName { get; set; }
    public string personOrganization { get; set; }
}

This is the code that I use to retrieve the data:

    private IEnumerable<PeopleList> GetPeople()
    {
        IEnumerable<PeopleList> peopleLists = null;

        var client = new WebClient();
        var data = client.DownloadData("https://localhost:44314/api/values");
        var stream = new MemoryStream(data);
        var obj = new DataContractJsonSerializer(typeof(string));
        var result = obj.ReadObject(stream).ToString();

        peopleLists = (IEnumerable<PeopleList>)JsonConvert.DeserializeObject<AllPeople>(result);            

        return peopleLists;
 }

I know the JsonConvert line is incorrect but I have been unsuccessful in figuring out how to convert the string into a list.

Any suggestions?

Thanks.

Upvotes: 0

Views: 35

Answers (1)

David
David

Reputation: 218818

In the JSON shown there's no property called data. So this isn't an instance of AllPeople. The JSON shown is just an array of PeopleList. (Which, incidentally, is a terrible name for a single instance of a "person".)

Deserialize it to a List<PeopleList>:

peopleLists = JsonConvert.DeserializeObject<List<PeopleList>>(result);

Upvotes: 2

Related Questions