我试图从雅虎财经中传输一些市场数据。 反序列化json流并将其写入控制台时遇到了一些麻烦。
我已经经历了几个堆栈溢出问题,试图将某些东西放在一起。
我不确定我是否将正确的代码组合在一起,因为我在将结果写入控制台时也遇到了问题。
来自雅虎的我的json数据看起来像这样:
{
"ResultSet":{
"Query":"genmab",
"Result":[
{
"symbol":"GNMSF",
"name":"Genmab A/S",
"exch":"PNK",
"type":"S",
"exchDisp":"OTC Markets",
"typeDisp":"Equity"
},
{
"symbol":"GE9.F",
"name":"Genmab A/S",
"exch":"FRA",
"type":"S",
"exchDisp":"Frankfurt",
"typeDisp":"Equity"
},
{
"symbol":"GEN.F",
"name":"GENMAB AS DK 1",
"exch":"FRA",
"type":"S",
"exchDisp":"Frankfurt",
"typeDisp":"Equity"
},
{
"symbol":"GE9.BE",
"name":"GENMAB AS DK 1",
"exch":"BER",
"type":"S",
"exchDisp":"Berlin",
"typeDisp":"Equity"
},
{
"symbol":"GE9.SG",
"name":"GENMAB AS Navne Aktier DK 1",
"exch":"STU",
"type":"S",
"exchDisp":"Stuttgart",
"typeDisp":"Equity"
},
{
"symbol":"GEN.CO",
"name":"Genmab A/S",
"exch":"CPH",
"type":"S",
"exchDisp":"Copenhagen",
"typeDisp":"Equity"
},
{
"symbol":"GEN.SG",
"name":"GENMAB AS Navne Aktier DK 1",
"exch":"STU",
"type":"S",
"exchDisp":"Stuttgart",
"typeDisp":"Equity"
},
{
"symbol":"GMXAY",
"name":"Genmab A/S",
"exch":"PNK",
"type":"S",
"exchDisp":"OTC Markets",
"typeDisp":"Equity"
},
{
"symbol":"GE9.DU",
"name":"GENMAB AS DK 1",
"exch":"DUS",
"type":"S",
"exchDisp":"Dusseldorf Stock Exchange",
"typeDisp":"Equity"
},
{
"symbol":"0MGB.IL",
"name":"GENMAB A/S GENMAB ORD SHS",
"exch":"IOB",
"type":"S",
"exchDisp":"International Orderbook - London",
"typeDisp":"Equity"
}
]
}
}
我提供的代码应该创建一个数据对象列表:
using System.Web.Script.Serialization;
public class DataObject
{
public string symbol { get; set; }
public string name { get; set; }
public string exch { get; set; }
public string type { get; set; }
public string exchDisp { get; set; }
public string typeDisp { get; set; }
}
public class RootObject
{
public DataObject[] resultSet { get; set; }
}
using (WebClient web = new WebClient())
{
string _url = "http://d.yimg.com/aq/autoc?query=genmab®ion=CO&lang=en-US";
var search = web.DownloadString(_url);
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<RootObject> oRootObject = serializer.Deserialize<List<RootObject>>(search);
然后我想将不同的数据写入控制台
foreach (var item in oRootObject)
{
Console.WriteLine(oRootObject.???.Value.name);
}
我已尝试DeBug流程但我无法看到任何数据进入对象列表。
由于 弗莱明
答案 0 :(得分:4)
格式化JSON之后,我可以看到你的类没有完全映射到你的JSON
我使用了一个非常方便的工具 - http://json2csharp.com来创建映射到json的类:
public class Result
{
public string symbol { get; set; }
public string name { get; set; }
public string exch { get; set; }
public string type { get; set; }
public string exchDisp { get; set; }
public string typeDisp { get; set; }
}
public class ResultSet
{
public string Query { get; set; }
public List<Result> Result { get; set; }
}
public class RootObject
{
public ResultSet ResultSet { get; set; }
}
然后你可以像以前那样做:
RootObject oRootObject = serializer.Deserialize<RootObject>(search);
内部oRootObject
是另一个对象 - ResultSet
内部ResultSet
是Result
列表 - 这就是您想要迭代的内容
你需要做这样的事情:
foreach (var item in oRootObject.ResultSet.Result)
{
Console.WriteLine(item.name);
}