sameera guntimadugu
sameera guntimadugu

Reputation: 49

mapping json property to existing model without changing name in the model

I have Json as

Addresses {
    Line1: "abc"
    Line2: "xyx"
}

I need to map to my existing model and I have used JsonProperty but I need to get Addr_1 and Addr_2 in the final response.

public class Addresses
{
     JsonProperty("Line1")
     public string Addr_1 {get; set;}
     JsonProperty("Line2")
     public string Addr_2 {get; set;}
}

Could any one help on this? Thanks in advance!

Upvotes: 0

Views: 132

Answers (1)

Vladimir D.
Vladimir D.

Reputation: 26

As I understand, you need to ignore the JsonProperty when serializing back to json.

You can use DefaultContractResolver class

Example:

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

public class Addresses
{
    [JsonProperty("Line1")]
    public string Addr_1 { get; set; }

    [JsonProperty("Line2")]
    public string Addr_2 { get; set; }
}

public class MyContractResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var list = base.CreateProperties(type, memberSerialization);

        foreach (var property in list)
            property.PropertyName = property.UnderlyingName;

        return list;
    }
}

public static class IgnoreJsonPropertyApp
{
    private static void Main(string[] args)
    {
        var originalJsonString = "{ \"Line1\": \"abc\", \"Line2\": \"xyx\"}";

        var addresses = JsonConvert.DeserializeObject<Addresses>(originalJsonString);

        var newJsonString = JsonConvert.SerializeObject(addresses, new JsonSerializerSettings { ContractResolver = new MyContractResolver() });

        Console.WriteLine($"originalJsonString={originalJsonString}");
        Console.WriteLine($"newJsonString={newJsonString}");
    }
}

Output:

originalJsonString={ "Line1": "abc", "Line2": "xyx"}  
newJsonString={"Addr_1":"abc","Addr_2":"xyx"}

Upvotes: 1

Related Questions