C# 从 HttpWebResponse 反序列化 JSON 的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13271158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Way to Deserialize JSON from HttpWebResponse
提问by user1798345
I'm trying to figure out the best way to parse incoming JSON server-side in .NET 3.5. I am receiving "title" from HttpWebResponse in JSON Formate. so i have to retrieve each title and store in the database. so please provide the code for retrieving each title.
我正在尝试找出在 .NET 3.5 中解析传入 JSON 服务器端的最佳方法。我从 HttpWebResponse 以 JSON 格式接收“标题”。所以我必须检索每个标题并存储在数据库中。所以请提供检索每个标题的代码。
public class MyObject
{
public ArrayList list { get; set; }
}
var request = WebRequest.Create("https://api.dailymotion.com/videos?fields=description,thumbnail_medium_url%2Ctitle&search=Good+Morning");
using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
string objText = reader.ReadToEnd();
MyObject myojb = (MyObject)js.Deserialize(objText, typeof(MyObject));
}
}
I am receiving Title in the myojb but how to retrieve Each Title from myojb.
我在 myojb 中收到标题,但如何从 myojb 中检索每个标题。
回答by Ademar
"I'm trying to figure out the best way to parse incoming JSON"
“我正在尝试找出解析传入 JSON 的最佳方法”
I would use json.net. Its so easy to deserialize/serialize json data.
我会使用 json.net。反序列化/序列化json数据非常容易。
Have a look here:
看看这里:
回答by James
Serialize into a dynamicobject
序列化为dynamic对象
using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objects = js.Deserialize<dynamic>(reader.ReadToEnd());
foreach (var o in objects)
{
Console.WriteLine(o["title"]);
}
}
回答by Furqan Safdar
Use this piece of code snippet to get Titleby using dynamicobject.
使用这段代码片段来获取Title使用dynamic对象。
.NET 4.0 and above
.NET 4.0 及以上
JavaScriptSerializer js = new JavaScriptSerializer();
var obj = js.Deserialize<dynamic>(reader.ReadToEnd());
foreach (var o in obj["list"])
{
var title = o["title"];
}
.NET 3.5 and below
.NET 3.5 及以下
JavaScriptSerializer js = new JavaScriptSerializer();
var obj = js.Deserialize<Dictionary<string, object>>(reader.ReadToEnd());
foreach (var o in (ArrayList)obj["list"])
{
if (o is Dictionary<string, object>)
var title = (o as Dictionary<string, object>)["title"];
}
Using Linq:
使用 Linq:
JavaScriptSerializer js = new JavaScriptSerializer();
var obj = js.Deserialize<Dictionary<string, object>>(reader.ReadToEnd());
var titles = ((ArrayList)obj["list"]).Cast<Dictionary<string, object>>()
.Select(s => s["title"].ToString()).ToArray<string>();

