Deserialize JSON to multiple properties

后端 未结 3 2108
刺人心
刺人心 2020-12-06 06:00

I am programming against a third party API which returns JSON data, but the format can be a little strange. Certain properties can either be an object (which contains an Id

3条回答
  •  情话喂你
    2020-12-06 06:22

    Try this (extend it with some thorough validation if you'll be using it in your code):

    public class MyObject
    {
        public ChildObject MyChildObject;
        public string MyChildObjectId;
    
        [JsonProperty("ChildObject")]
        public object ChildObject
        {
            get
            {
                return MyChildObject;
            }
            set
            {
                if (value is JObject)
                {
                    MyChildObject = ((JToken)value).ToObject();
                    MyChildObjectId = MyChildObject.Id;
                }
                else
                {
                    MyChildObjectId = value.ToString();
                    MyChildObject = null;
                }
            }
        }
    }
    

提交回复
热议问题