Home > Mobile >  How to map json response to the model with different field names
How to map json response to the model with different field names

Time:01-31

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
    }

CodePudding user response:

Use the JsonPropertyName attribute

public class Model
{
    [JsonPropertyName("items")]
    public SomeEntity[] Items { get; set; }
}    
        
public class SomeEntity
{
    [JsonPropertyName("A")]
    public int MyA { get; set; } // map to A
    [JsonPropertyName("User")]
    public User MyUser { get; set; } // map to User
}
        
public class User
{
    public string Name { get; set; }
    [JsonPropertyName("Age")]
    public string MyAge { get; set; } // map to Age
}

You can then deserialize it with something like

JsonSerializer.Deserialize<Model>(response);

CodePudding user response:

try this please

[JsonConverter(typeof(JsonPathConverter))]
   public class SomeEntity
    {
        [JsonProperty("items.User.Name")]
        public string UserName{ get; set; } // map to User.Name
    }

deserialize using :


JsonSerializer.Deserialize<SomeEntity>(response);
  •  Tags:  
  • Related