0

我有一个来自 web api 的 JSON 响应,因为

{"payload":{"items":{"11204":{"title":"The Ugliest Girl?","item_id":"11204","thumb_url":"http:google.11204.jpg","teaser":"We live in the internet generationher purpose in life to her through this adversity.","language_id":"en","media_id":1,"views":"5","shares":"0"},"11228":{"title":"Depressed","item_id":"11228","thumb_url":"http:google.11228.jpg","teaser":"We all get discouraged at times, especially when things go wrong or other people hurt us. Sometimes we can seem to go through a string of disappointments that compound our sadness till we wonder.","language_id":"en","media_id":5,"views":"35","shares":"2"}} 

以及更多类似的对象

我如何将其解析为 Dictionary 或以任何其他方式?响应因请求而异。

4

2 回答 2

0

您可以将您的 json 解析为如下对象:

var parsed = JObject.Parse(Json);

并获得一个特定的价值:

var value = parsed[key];
于 2013-08-06T10:40:22.497 回答
0

使用json2csharp.com 之类的服务,您可以将 json 转换为 C#。鉴于您拥有的 json,您将需要稍微修改类。这里是消耗品类

public class Item
{
    public string title { get; set; }
    public string item_id { get; set; }
    public string thumb_url { get; set; }
    public string teaser { get; set; }
    public string language_id { get; set; }
    public int media_id { get; set; }
    public string views { get; set; }
    public string shares { get; set; }
}

public class Payload
{
    public ICollection<Item> Items { get; set; }
}

从那里您可以使用 Json.Net 之类的库将 json 转换为这些对象。通常您可以直接转换为您的类,但由于名称中的索引,这是不可能的。所以你必须自己做一些转换。

public Payload ConvertJson(string json)
{
    var payload = new Payload();

    var container = JToken.Parse(json) as JContainer;
    if(container == null) return payload;

    payload.Items = new List<Item>(container.Count);

    foreach (var child in container)
    {
        var childJson = child.FirstOrDefault();
        if (childJson == null) continue;

        var item = childJson.ToObject<Item>();
        if (item.item_id == 0)
        {
            item.item_id = Convert.ToInt32(((JProperty)child).Name);
        }
        payload.Items.Add(item);
    }
    return payload;
}
于 2013-08-06T22:48:17.047 回答