0

I have an entity class with JsonProperty attribute as follows:

public class Book
{
    [JsonProperty("id")]
    public long BookId { get; set; }
    [JsonProperty("name")]
    public string BookName { get; set; }
}

I want to deserialize this from JSON string to the entity. Due to JsonProperty id & name, the json should have the id/name schema and in that case the deserialize works perfectly (as expected). But in some cases, the json string can also have BookId and BookName. Can I have multiple JsonProperty attributes to handle this? Or is there a way to let the serializer know, that if not id then deserialize using BookId? Or any other way to handle this use case?

Karney.
  • 4,803
  • 2
  • 7
  • 11
  • 1
    This link might help you https://stackoverflow.com/questions/43714050/multiple-jsonproperty-name-assigned-to-single-property – Arib Yousuf Mar 02 '21 at 07:38

2 Answers2

0

You can replace the property name before deserializing the json.

var book = @"
    [
      {
        'id': 123456789,
        'name': 'book1'
      },
      {
        'BookId': 1234567,
        'BookName': 'book2'
      }
    ]
    ";

    var after = book.Replace("BookId", "id").Replace("BookName", "name");
    var sbook = JsonConvert.DeserializeObject<List<Book>>(after);

Then you can get the entire deserialization object.

enter image description here

derloopkat
  • 6,232
  • 16
  • 38
  • 45
Karney.
  • 4,803
  • 2
  • 7
  • 11
0

You could solve this by defining alternative properties, which redirects to existing ones. For example,

public class Book
{
    [JsonProperty("bookId")]
    public long BookId { get; set; }
    
    [JsonProperty("id")]
    private long Id
    {
        get => BookId;
        set => BookId = value;
    }
    [JsonProperty("bookName")]
    public string BookName { get; set; }
    
    [JsonProperty("name")]
    private string Name
    {
        get => BookName;
        set => BookName = value;
    }
}

Demo

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51