1

I have a class that is deserialized using JSonConvert:

public class TaskEntity{
    [Ignore]
    public Address Addresses { get; set; }
    [JsonProperty(PropertyName = "Addresses.Street1")]
    public string Street1 { get; set; }
    public string Street2 { get; set; }
    public string Number { get; set; }
    public string Box { get; set; }
    public string ZipCode { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}
public class Address
{
    public string Street1 { get; set; }
    public string Street2 { get; set; }
    public string Number { get; set; }
    public string Box { get; set; }
    public string ZipCode { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public override string ToString()
    {
        return string.Format("{0} {1}{2}, {3} {4}, {5}",
            Street1,
            Number,
            (string.IsNullOrEmpty(Box) ? "" : " " + Box),
            ZipCode,
            City,
            Country);
    }
}

Actually when I deserialize the object the Addresses is fill with data and I'm looking for a way to tell to JsonConvert to fill Street1 with the same data that for Addresses.Street1.

Here I tried with a JsonProperty(PropertyName = "Addresses.Street1") but it doesn't work.

I tried with Custom JsonConverter but can't figure really how to make it. I would like to have something generic that can apply to all class that have a property of type Address.

My unit test is quite simple:

[TestMethod]
    public void JsonConvert_CustomResolver_ShouldConvertAddressTypeToFlatBasicProperties()
    {
        var tasksSerialized = JsonConvert.SerializeObject(new TaskEntity
        {
          Addresses  = new Address
          {
              Street1 = LocationFaker.Street()
          }
        });
        Console.Write(tasksSerialized);

        var taskEntities = JsonConvert.DeserializeObject<TaskEntity>(tasksSerialized);
        Assert.IsNotNull(taskEntities.Street1);
    }

Fiddle: https://dotnetfiddle.net/MQmhNA

klashar
  • 2,519
  • 2
  • 28
  • 38
Jerome2606
  • 933
  • 20
  • 42

1 Answers1

0

Finally found a solution with a JsonConverter like this answer Can I specify a path in an attribute to map a property in my class to a child property in my JSON?

Here is the working fiddle: https://dotnetfiddle.net/x6w1MR

Community
  • 1
  • 1
Jerome2606
  • 933
  • 20
  • 42