JSON.Net获取动态对象

时间:2015-07-20 15:38:46

标签: c# json

我不认为这篇文章的标题解释了问题所在,但我不知道如何说出来。 基本上我从API无法控制的响应:

        "variations":{  
            "1033308042319364133":{  
                "id":"1033308042319364133",
                "order":null,
                "created_at":"2015-07-20 13:45:45",
                "updated_at":"2015-07-20 13:47:11",
                "title":"Male",
                "mod_price":"+0.00",
                "modifier":1033306667720114205,
                "product":0,
                "difference":"+£0.00"
            },
            "1033308953984892967":{  
                "id":"1033308953984892967",
                "order":null,
                "created_at":"2015-07-20 13:47:34",
                "updated_at":"2015-07-20 13:47:34",
                "title":"Female",
                "mod_price":"+0.00",
                "modifier":1033306667720114205,
                "product":0,
                "difference":"+£0.00"
            },
            "1033309404260204585":{  
                "id":"1033309404260204585",
                "order":null,
                "created_at":"2015-07-20 13:48:27",
                "updated_at":"2015-07-20 13:48:27",
                "title":"Male (Junior)",
                "mod_price":"+0.00",
                "modifier":1033306667720114205,
                "product":0,
                "difference":"+£0.00"
            },
            "1033309540147265579":{  
                "id":"1033309540147265579",
                "order":null,
                "created_at":"2015-07-20 13:48:44",
                "updated_at":"2015-07-20 13:48:44",
                "title":"Female (Junior)",
                "mod_price":"+0.00",
                "modifier":1033306667720114205,
                "product":0,
                "difference":"+£0.00"
            }
        }

在我的c#代码中,我循环遍历这样的变体:

// Get our child variants
var variations = model["variations"];
var IsNull = IsJTokenNull(variations);
var variants = !IsNull ? new List<VariationResponseModel>() : null;

// If we have some variations
if (!IsNull)
{

    // Loop through our variations
    foreach (var variant in variations)
    {

        // Add our variant to our list
        variants.Add(CreateVariants(variant.First));
    }
}

如您所见,我使用 variant.First 来选择属性中的对象。我的问题是,这是最好的方法吗?这似乎是一个可怕的黑客。

1 个答案:

答案 0 :(得分:1)

这看起来像.net Dictionary而不是列表。如果VariationResponseModel具有正确的属性,您可以执行以下操作:

var variants = JsonConvert.DeserializeObject<Dictionary<string, Variant>>(variations);

或使用JObject

var variants = JObject.Parse(variations).ToObject<Dictionary<string, Variant>>();

两种方法都是等价的,并假设您将输入作为JSON字符串。如果您的输入已经是JObject,则可以使用:

var variants = variations.ToObject<Dictionary<string, Variant>>()

如果您之后需要列表中的变体/可枚举,请使用variants.Values

(JsonConvert / JObject来自Json.net反序列化器)