2022-01-31

How to map json response to the model with different field names

I am using an ASP.NET Core 6 and System.Text.Json library.

For example, I'm getting a response from the some API with the following structure

{
   "items": 
   [
       {
          "A": 1,
          "User": 
          {
             "Name": "John",
             "Age": 21,
             "Adress": "some str"
          },
       },
       {
          "A": 2,
          "User": 
          {
             "Name": "Alex",
             "Age": 22,
             "Adress": "some str2"
          },
       }
   ]
}

And I want to write this response to the model like List<SomeEntity>, where SomeEntity is

    public class SomeEntity
    {
        public int MyA { get; set; } // map to A
        public User MyUser { get; set; } // map to User
    }

    public class User
    {
        public string Name { get; set; }
        public string MyAge { get; set; } // map to Age
    }

How could I do it?

UPDATE:

Is it possible to map nested properties?

    public class SomeEntity
    {
        // should I add an attribute [JsonPropertyName("User:Name")] ?
        public string UserName{ get; set; } // map to User.Name
    }


from Recent Questions - Stack Overflow https://ift.tt/Nq1WXhbSu
https://ift.tt/Mhf8FyP6J

No comments:

Post a Comment