How to Map Json String to a Model in ASP.NET Core?

In this post, we are using .NET Core (.NET 6), we are trying to map a Json string to a class model in ASP.NET Core Web app. Here is the Json string:

{
   "items": 
   [
       {
          "ID": 1,
          "User": 
          {
             "FirstName": "John",
             "LastName": "Smith",
             "PhoneNumber": "50-745671",
             "Address": "804 Foster Avenue"
          },
       },
       {
          "ID": 2,
          "User": 
          {
             "Name": "Alex",
             "LastName": "Dylan",
             "PhoneNumber": "45-234965",
             "Address": "176 Bradford St"
          },
       }
   ]
}

We want to map this Json string to a generic list in .NET such as List<SomeEntity> where we don't have same naming as in the Json string, we will use JsonPropertyName attribute to map the fields, here is how the model should:

public class Model
{
    [JsonPropertyName("items")]
    public SomeEntity[] Items { get; set; }
}    
        
public class SomeEntity
{
    [JsonPropertyName("ID")]
    public int MyID { get; set; } // map to ID
    [JsonPropertyName("User")]
    public User MyUser { get; set; } // map to User
}
        
public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNumber { get; set; }
    [JsonPropertyName("Address")]
    public string MyAddress { get; set; } // map to Address
}

You can then deserialize the response using JsonSerializer as per the the following syntax:

JsonSerializer.Deserialize<Model>(response);

Of course it is better to have same naming convention between the Json string and the C# model class, but in some cases we don't have privileges to modify the Json string, therefore we should adjust our model class to map the fields.

Post a Comment

Previous Post Next Post