ozziem
ozziem

Reputation: 305

How add dynamically [JsonProperty("")] annotarion to properties for purporse of serializing JSON?

I wanted to add [JsonProperty("")] dynamically , how can I achieve this?

class Address
{
     public string Number { get; set; }
     public string Street { get; set; }
     public string City { get; set; }
     public string Country { get; set; }
}

class Person
{
     public string Name { get; set; }
     public int Age { get; set; }
     public Address PostalAddress { get; set; }
}

F.e I wanted to add [JsonProperty("")] annotation to nested class at runtime.

 class Address
    {    [JsonProperty("Nmb")]
         public string Number { get; set; }
          [JsonProperty("Str")]
         public string Street { get; set; }
         public string City { get; set; }
         public string Country { get; set; }
    }

I need to add dynamically because the class I use is coming from other library. My target aim is getting serialized json with shortened attribute names. How can I do this?

Upvotes: 0

Views: 1148

Answers (2)

ozziem
ozziem

Reputation: 305

For my question, there is no proper method to add annotations at runtime. But to serialize json, if we need customSerialization, like the answer posted above , we can do stg like this: (The above answer wont be proper for nested class to me, if we identify class names, we need to use this way)

https://stackoverflow.com/a/33290710/1133217

Also this way prevents from creating unneccesary objects for serializing by using

 public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();

When user clicks first time , it will be created, when browser is open , even other request come , it wont be created twice. Plus this way we can identify class names, and guarantte which attribute will change in which class.

Upvotes: 0

Rithik Banerjee
Rithik Banerjee

Reputation: 467

You can use Newtonsoft.Json.Serialization's ContractResolver for this purpose, define all the property-to-property mapping for json that needs to be serialized or de-serialized. Sample:

public class CustomContractResolver : DefaultContractResolver
{
    private Dictionary<string, string> PropertyMappings { get; set; }

    public CustomContractResolver()
    {
        this.PropertyMappings = new Dictionary<string, string>
        {
            {"Number", "Nmb"},
            {"Street", "Str"},
            //all properties,
        };
    }

    protected override string ResolvePropertyName(string propertyName)
    {
        string resolvedName = null;
        var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
        return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
    }
}

Here is how to use it:

var jsonObject = JsonConvert.DeserializeObject(jsonString, new JsonSerializerSettings{ ContractResolver = new CustomContractResolver() });

Upvotes: 1

Related Questions