遍历JSON对象在C# [英] Iterating over JSON object in C#
本文介绍了遍历JSON对象在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在C#中使用JSON.NET解析来自API的Klout的响应。我的回答是这样的:
[
{
ID:5241585099662481339
显示名:音乐,
名:音乐,
弹头:音乐,
图片网址:http://kcdn3.klout.com/static/images/music-1333561300502.png
},
{
ID:6953585193220490118
显示名:名人,
名:名人,
塞:名人,
图片网址:http://kcdn3.klout.com/static/images/topics/celebrities_b32741b6703151cc7bd85fba24c44c52.png
},
{
ID:5757029936226020304
显示名:娱乐,
名:娱乐,
塞:娱乐,
图片网址:http://kcdn3.klout.com/static/images/topics/Entertainment_7002e5d2316e85a2ff004fafa017ff44.png
},
{
ID:3718
显示名:周六夜现场,
名:周六夜现场,
塞:周六夜现场
图片网址:http://kcdn3.klout.com/static/images/icons/generic-topic.png
},
{
ID:8113008320053776960
显示名:好莱坞,
名:好莱坞,
塞:好莱坞,
图片网址:http://kcdn3.klout.com/static/images/topics/hollywood_9eccd1f7f83f067cb9aa2b491cd461f3.png
}
]
正如你所见,它包含5 ID
标记。也许下一次将是6或1或其他一些数字。我想遍历JSON和获得每个 ID
标记的值。我无法不知道有多少会运行一个循环。我怎样才能解决这个问题?
解决方案
动态dynJson = JsonConvert.DeserializeObject(JSON);
的foreach(在dynJson VAR项)
{
Console.WriteLine({0} {1} {2} {3} \\ n,item.id,item.displayName,
item.slug,item.imageUrl);
}
或
VAR列表= JsonConvert.DeserializeObject<名单,LT; MyItem>>(JSON);公共类MyItem
{
公共字符串ID;
公共字符串显示名;
公共字符串名称;
公共字符串蛞蝓;
公共字符串图片网址;
}
I am using JSON.NET in C# to parse a response from the Klout API. My response is like this:
[
{
"id": "5241585099662481339",
"displayName": "Music",
"name": "music",
"slug": "music",
"imageUrl": "http://kcdn3.klout.com/static/images/music-1333561300502.png"
},
{
"id": "6953585193220490118",
"displayName": "Celebrities",
"name": "celebrities",
"slug": "celebrities",
"imageUrl": "http://kcdn3.klout.com/static/images/topics/celebrities_b32741b6703151cc7bd85fba24c44c52.png"
},
{
"id": "5757029936226020304",
"displayName": "Entertainment",
"name": "entertainment",
"slug": "entertainment",
"imageUrl": "http://kcdn3.klout.com/static/images/topics/Entertainment_7002e5d2316e85a2ff004fafa017ff44.png"
},
{
"id": "3718",
"displayName": "Saturday Night Live",
"name": "saturday night live",
"slug": "saturday-night-live",
"imageUrl": "http://kcdn3.klout.com/static/images/icons/generic-topic.png"
},
{
"id": "8113008320053776960",
"displayName": "Hollywood",
"name": "hollywood",
"slug": "hollywood",
"imageUrl": "http://kcdn3.klout.com/static/images/topics/hollywood_9eccd1f7f83f067cb9aa2b491cd461f3.png"
}
]
As you see, it contains 5 id
tags. Maybe next time it would be 6 or 1 or some other number. I want to iterate over the JSON and get the value of each id
tag. I can't run a loop without knowing how many there will be. How can I solve this?
解决方案
dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
Console.WriteLine("{0} {1} {2} {3}\n", item.id, item.displayName,
item.slug, item.imageUrl);
}
or
var list = JsonConvert.DeserializeObject<List<MyItem>>(json);
public class MyItem
{
public string id;
public string displayName;
public string name;
public string slug;
public string imageUrl;
}
这篇关于遍历JSON对象在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文