WebApi - Deserializing and serializing alternate property names

前端 未结 2 578
清歌不尽
清歌不尽 2020-12-10 04:38

I\'m trying to figure out how I can specify alternate property names with ASP.NET WebApi - and have it work for deserialization + serialization, and for JSON + XML. I\'ve on

相关标签:
2条回答
  • 2020-12-10 05:09

    You can force Asp.Net to use the JSON deserializer by passing a JObject to your action, although it is a bit annoying to have to do it like this.

    Then you can work with it as a JObject or call .ToObject<T>(); which will then honor the JsonProperty attribute.

    // POST api/values
    public IHttpActionResult Post(JObject content)
    {
        var test = content.ToObject<TestSerialization>();
        // now you have your object with the properties filled correctly.
        return Ok();
    }
    
    0 讨论(0)
  • 2020-12-10 05:15

    Some of your findings/conclusions are incorrect...you can try the following instead:

    This should work for both default Xml & Json formatters of web api and for both serialization & deserialization.

    [DataContract]
    public class TestSerialization
    {
        [DataMember(Name = "field_one")]
        public string ItemOne { get; set; }
    
        [DataMember(Name = "field_two")]
        public string ItemTwo { get; set; }
    }
    

    The following should work for Json formatter only and for both serialization & deserialization.

    public class TestSerialization
    {
        [JsonProperty(PropertyName = "field_one")]
        public string ItemOne { get; set; }
    
        [JsonProperty(PropertyName = "field_two")]
        public string ItemTwo { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题