【问题标题】:Handling different JSON into class properties [duplicate]将不同的 JSON 处理为类属性 [重复]
【发布时间】:2020-08-28 13:34:51
【问题描述】:

我们的 WEB API 收到不同的响应,如下所示:

格式 1:

{
    "Data": {
        "CarDetails": {
            a
        }
    }
}

格式 2:

{
    "Data": {
        "CarDetails": [
            {
                a
            },
            {
                b
            }
        ]
    }
}

对于第一个,我们使用如下属性:

格式一:

public CarDetails CarDetails { get; set; }

格式二:

public List<CarDetails> CarDetails { get; set; }

那么有没有办法在属性部分动态处理这种类型的代码?

【问题讨论】:

    标签: c# asp.net json deserialization json-deserialization


    【解决方案1】:

    我在使用 API 时遇到了类似的情况。我所做的只是公开一个List&lt;T&gt; 属性,并在我的实现内部检查即将到来的对象是单个对象还是集合。这是我的代码。

    首先使用Object类型属性进行反序列化。

        private Object _leg;
        [JsonProperty("Leg")]
        public Object Leg
        {
            get => _leg;
            set
            {
                _leg = value;
                Legs = ParseLegs(value);
            }
        }
    

    然后在您的场景中为List&lt;CarDetails&gt; 添加属性,我有Leg,在getter 中我有如下逻辑:

        [JsonIgnore]
        public List<Leg> Legs { get; private set; }
    
        private List<Leg> ParseLegs(object json)
        {
            // case for multiple legs in response
            if (json is JArray array)
                return array.ToObject<List<Leg>>();
    
            if (!(json is JObject @object)) return new List<Leg>();
    
            return new List<Leg>() {  @object.ToObject<Leg>()};
        }
    }
    

    只需将您的Leg 类型替换为CarDetails,它应该对您有好处。

    您的类结构如下所示:

        private Object _carDetail;
        [JsonProperty("CarDetails")]
        public Object CarDetail
        {
            get => _carDetail;
            set
            {
                _carDetail = value;
                CarDetails = ParseCarDetails(value);
            }
        }
    

    其他属性是:

        [JsonIgnore]
        public List<CarDetails> CarDetails { get; private set; }
    
        private List<CarDetails> ParseCarDetails(object json)
        {
            // case for multiple cardetails in response
            if (json is JArray array)
                return array.ToObject<List<CarDetails>>();
    
            if (!(json is JObject @object)) return new List<CarDetails>();
    
            return new List<CarDetails>() {  @object.ToObject<CarDetails>()};
        }
    

    希望对你有所帮助。

    【讨论】:

    猜你喜欢
    • 2019-08-02
    • 1970-01-01
    • 2013-09-02
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多