C# WP7中的JSON响应解析
我有一个来自web api的JSON响应,如下所示C# WP7中的JSON响应解析,c#,json,windows-phone-7,C#,Json,Windows Phone 7,我有一个来自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":"e
{"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"}}
还有更多类似的物体
如何将其解析为字典或任何其他方式?响应因请求而异 u可以将json解析为如下对象:
var parsed = JObject.Parse(Json);
要获得特定值,请执行以下操作:
var value = parsed[key];
使用像您这样的服务可以将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; }
}
公共类项目
{
公共字符串标题{get;set;}
公共字符串项_id{get;set;}
公共字符串thumb_url{get;set;}
公共字符串摘要程序{get;set;}
公共字符串语言_id{get;set;}
public int media_id{get;set;}
公共字符串视图{get;set;}
公共字符串共享{get;set;}
}
公共类有效载荷
{
公共ICollection项{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;
}
public-Payload-ConvertJson(字符串json)
{
var有效载荷=新有效载荷();
var container=JToken.Parse(json)作为JContainer;
if(container==null)返回有效负载;
有效载荷.Items=新列表(container.Count);
foreach(容器中的变量子项)
{
var childJson=child.FirstOrDefault();
如果(childJson==null)继续;
var item=childJson.ToObject();
if(item.item_id==0)
{
item.item_id=Convert.ToInt32(((JProperty)child.Name);
}
有效载荷.项目.添加(项目);
}
返回有效载荷;
}