我有来自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或以其他任何方式?响应因请求而异。
答案 0 :(得分:0)
你可以将你的json解析成如下对象:
var parsed = JObject.Parse(Json);
并获得特定值:
var value = parsed[key];
答案 1 :(得分: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;
}