解析多个股票报价的json字符串

时间:2013-08-07 21:30:25

标签: json

这是从“JNJ”和“ADP”股票信息请求返回的数据。

var quote = new Object(); 
    quote['JNJ'] = {
    Ticker: 'JNJ', 
    Valoren: 943981, 
    ExchangeCode: 321, 
    Exchange: 'NY', 
    ExchangeName: 'New York Stock Exchange', 
    ExchangeShortName: 'NYSE', 
    TradeTime: 1375906505,
    Volume: 9052146, 
    Last: 93.66, 
    Open: 93.60, 
    High: 94.03, 
    Low: 93.47,
    PrevClose: 93.81, 
    Change: -0.15, 
    ChangePercent: -0.1599, 
    Bid: 93.66,
    Ask: 93.68, 
    BidSize: 2500, 
    AskSize: 800, 
    Name: 'Johnson & Johnson',
    ShortName: 'Johnson', 
    ISIN: 'US4781601046', 
    SharesOutstanding: 2818073863
}; 
quote['ADP'] = {
    Ticker: 'ADP', 
    Valoren: 910042,
    ExchangeCode: 537, 
    Exchange: 'NQ', 
    ExchangeName: 'Nasdaq Stock Market', 
    ExchangeShortName: 'Nasdaq', 
    TradeTime: 1375905600, 
    Volume: 1460941, 
    Last: 71.99, 
    Open: 72.11, 
    High: 72.28, 
    Low: 71.67, 
    PrevClose: 72.24, 
    Change: -0.25, 
    ChangePercent: -0.3461, 
    Bid: 71.99, 
    Ask: 72.00, 
    BidSize: 9300, 
    AskSize: 300, 
    Name: 'Automatic Data Processing',
    ShortName: 'Automatic Data', 
    ISIN: 'US0530151036', 
    SharesOutstanding: 485222417
}; 
eval('updateQuotes(quote)');

我是新手。我试过json.net,但我继续得到错误。看来json不合适。我认为可能在“{”之前和“}”之后剥离一切,但到目前为止还没有运气。任何帮助或想法将不胜感激。

编辑: 通过将它限制为单个股票,然后剥离“{”之后和“}”之后的所有内容,我可以使用以下方法解析它:

string input = json;
var jss = new JavaScriptSerializer();
Dictionary<string, string> sData = jss.Deserialize<Dictionary<string, string>>(json);
string _Ticker = sData["Ticker"].ToString();
string _Last = sData["Last"].ToString();
Console.WriteLine(_Ticker + "  " + _Last);

1 个答案:

答案 0 :(得分:1)

尝试删除最后的 eval('updateQuotes(quote)')同时检查要反序列化的对象是否为此格式

public class RootObject
{

public string Ticker { get; set; }
public int Valoren { get; set; }
public int ExchangeCode { get; set; }
public string Exchange { get; set; }
public string ExchangeName { get; set; }
public string ExchangeShortName { get; set; }
public int TradeTime { get; set; }
public int Volume { get; set; }
public double Last { get; set; }
public double Open { get; set; }
public double High { get; set; }
public double Low { get; set; }
public double PrevClose { get; set; }
public double Change { get; set; }
public double ChangePercent { get; set; }
public double Bid { get; set; }
public double Ask { get; set; }
public int BidSize { get; set; }
public int AskSize { get; set; }
public string Name { get; set; }
public string ShortName { get; set; }
public string ISIN { get; set; }
public int SharesOutstanding { get; set; }
}

您可以使用此http://json2csharp.com/

验证任何json字符串到C#对象