user12398280
user12398280

Reputation: 137

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
    }

Upvotes: 1

Views: 8341

Answers (2)

Amjad S.
Amjad S.

Reputation: 1241

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);

Upvotes: 1

Hans Kilian
Hans Kilian

Reputation: 25090

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);

Upvotes: 3

Related Questions