Deserialize two values into the same property

后端 未结 2 1840
被撕碎了的回忆
被撕碎了的回忆 2021-01-25 08:55

I have a client which can call two different versions of a service.

One service only sends a single value:

{
  \"value\" : { ... }
}

T

2条回答
  •  灰色年华
    2021-01-25 09:31

    Rather than writing a JsonConverter, you could make a set-only property Value on your MyValues, like so:

    public class MyValues
    {
        [JsonProperty]
        Stuff Value
        {
            set
            {
                (Values = Values ?? new List(1)).Clear();
                Values.Add(value);
            }
        }
    
        public List Values { get; set; }
        public Thing Other { get; set; }
    }
    

    It could be public or private if marked with [JsonProperty]. In this case Json.NET will call the Value setter if the singleton "value" property is encountered in the JSON, and call the Values setter if the array "values" property is encountered. Since the property is set-only only the array property will be re-serialized.

提交回复
热议问题