multiple JsonProperty Name assigned to single property

后端 未结 2 1613
悲哀的现实
悲哀的现实 2020-12-09 01:22

I have two format of JSON which I want to Deserialize to one class. I know we can\'t apply two [JsonProperty] attribute to one property.

Can you please

相关标签:
2条回答
  • 2020-12-09 01:45

    Tricking custom JsonConverter worked for me. Thanks @khaled4vokalz, @Khanh TO

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            object instance = objectType.GetConstructor(Type.EmptyTypes).Invoke(null);
            PropertyInfo[] props = objectType.GetProperties();
    
            JObject jo = JObject.Load(reader);
            foreach (JProperty jp in jo.Properties())
            {
                if (string.Equals(jp.Name, "name1", StringComparison.OrdinalIgnoreCase) || string.Equals(jp.Name, "name2", StringComparison.OrdinalIgnoreCase))
                {
                    PropertyInfo prop = props.FirstOrDefault(pi =>
                    pi.CanWrite && string.Equals(pi.Name, "CodeModel", StringComparison.OrdinalIgnoreCase));
    
                    if (prop != null)
                        prop.SetValue(instance, jp.Value.ToObject(prop.PropertyType, serializer));
                }
            }
    
            return instance;
        }
    
    0 讨论(0)
  • 2020-12-09 01:48

    A simple solution which does not require a converter: just add a second, private property to your class, mark it with [JsonProperty("name2")], and have it set the first property:

    public class Specifications
    {
        [JsonProperty("name1")]
        public string CodeModel { get; set; }
    
        [JsonProperty("name2")]
        private string CodeModel2 { set { CodeModel = value; } }
    }
    

    Fiddle: https://dotnetfiddle.net/z3KJj5

    0 讨论(0)
提交回复
热议问题