所以这是我的代码:
// converts JSON data to an object I can use to pull select data out of
JObject o = JObject.Parse(data);
// this works fine. I can go one layer deep for a single piece of data
int count = (int)o["count"];
Console.WriteLine("This: {0} should say 30", count);
// this also works. I can go multiple layers deep for SINGLE pieces of data...
string publisherOne = (string)o["recipes"][0]["publisher"];
Console.WriteLine("This: {0} should say Closet Cooking", publisherOne);
// this is where the issue is... I can't go multiple layers deep and
// get single pieces of data from each JSON object
List<string> allPublishers = o["recipes"]["publisher"].Select(t => (string)t).ToList();
Console.WriteLine(allPublishers[2] + "should say picky palate");
数据是一串JSON,这里是我正在使用的样本:(它更长,但这已经足够了)
{
"count": 30,
"recipes": [
{
"publisher": "Closet Cooking",
"f2f_url": "http://food2fork.com/view/35186",
"title": "Caprese Grilled Cheese Sandwich",
"source_url": "http://www.closetcooking.com/2011/09/caprese-grilled-cheese-sandwich.html",
"recipe_id": "35186",
"image_url": "http://static.food2fork.com/Caprese2BGrilled2BCheese2BSandwich2B5002B21616ce448f5.jpg",
"social_rank": 99.99999999999993,
"publisher_url": "http://closetcooking.com"
},
{
"publisher": "Closet Cooking",
"f2f_url": "http://food2fork.com/view/35596",
"title": "Spinach Pesto Grilled Cheese Sandwich",
"source_url": "http://www.closetcooking.com/2010/05/spinach-pesto-grilled-cheese-sandwich.html",
"recipe_id": "35596",
"image_url": "http://static.food2fork.com/SpinachPestoGrilledCheeseSandwich50053b8a9a0.jpg",
"social_rank": 99.99999999999862,
"publisher_url": "http://closetcooking.com"
},
{
"publisher": "Picky Palate",
"f2f_url": "http://food2fork.com/view/484d98",
"title": "Crock Pot Pesto Ranch Chicken Thighs",
"source_url": "http://picky-palate.com/2012/09/20/pesto-ranch-crock-pot-chicken-thighs/",
"recipe_id": "484d98",
"image_url": "http://static.food2fork.com/CrockPotPestoRanchChickenThighs1text1300x248ca0b.jpg",
"social_rank": 99.99999999941502,
"publisher_url": "http://picky-palate.com"
},
前两个(count和publisherOne)工作非常好。 allPublishers应该是所有发布者的列表,但它会给我带来麻烦,因为发布者信息只是食谱数组中的一个数据。这是我在尝试这样做时使用的参考: http://www.newtonsoft.com/json/help/html/LINQtoJSON.htm 提前谢谢!
答案 0 :(得分:0)
我会使用这些类
public class Recipe
{
public string publisher { get; set; }
public string f2f_url { get; set; }
public string title { get; set; }
public string source_url { get; set; }
public string recipe_id { get; set; }
public string image_url { get; set; }
public double social_rank { get; set; }
public string publisher_url { get; set; }
}
public class RootObject
{
public int count { get; set; }
public List<Recipe> recipes { get; set; }
}
和
反序列化为
var obj = JsonConvert.DeserializeObject<RootObject>(json)
现在您可以用编译时安全方式编写linq