Razor JSON to list

Skythrust

Member
Jul 9, 2019
127
6
Hi all,

I was wondering if there are any possibilities to show all values from an JSON output in a list.

For now I am able to show just one value, but in the foreach I would like to show them all.
C#:
c#

JSON output/response is; [{"FrstName": "John","LastName": "Doe","MiddleName": null,},{"FrstName": "Jane","LastName": "Doe","MiddleName": null,},{"FrstName": "Hope","LastName": "Dyne","MiddleName": van,}]

dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content);

Persons = new List<Person>();

Persons.Add(new Person()
{
    FrstName = jsonResponse.FrstName, // FrstName = jsonResponse[0].FrstName
    LastName = jsonResponse.LastName, // LastName = jsonResponse[0].LastName
    MiddleName = jsonResponse.MiddleName, // MiddleName = jsonResponse[0].MiddleName
});

with the [0] it works for just one record.
 

JayCustom

Always Learning
Aug 8, 2013
5,472
1,385
Instead of deserializing into a dynamic, pass in a list of person and deserialize directly to your list.

var Persons = JsonConvert.DeserializeObject<List<Person>>(json);
 

Skythrust

Member
Jul 9, 2019
127
6
Instead of deserializing into a dynamic, pass in a list of person and deserialize directly to your list.

var Persons = JsonConvert.DeserializeObject<List<Person>>(json);
With using "FrstName = jsonResponse.FrstName" or something else?

Since when I try to add a new person to a list VS is giving me an error that FrstName does not contain a definition.
 
Last edited:

TheGeneral

Active Member
Dec 27, 2016
100
113
Using System.Text.Json (NOT Newtonsoft) you can do this quite easily:

C#:
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string MiddleName { get; set; }
    }

    public static class RazorCode
    {
        private static readonly JsonSerializerOptions Options = new()
        {
            PropertyNameCaseInsensitive = true
        };

        public static void Render()
        {
            var people = JsonSerializer.Deserialize<List<Person>>("string input", Options);
        }
    }
 

Users who are viewing this thread

Top