JsonReaderException.如何将 JSON 转换为 ASP.NET C# 字符串



我想从查询中获取雅虎财经股票信息到我的 ASP.NET 应用程序中,以将其显示为GridView。查询返回如下所示的 JSON:

YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"zumtobel","Result":[{"symbol":"ZMTBF","name":"ZUMTOBEL AG","exch":"PNK","type":"S","exchDisp":"OTC Markets","typeDisp":"Equity"},{"symbol":"ZAG.VI","name":"ZUMTOBEL GR","exch":"VIE","type":"S","exchDisp":"Vienna","typeDisp":"Equity"},{"symbol":"T9Z.SG","name":"ZUMTOBEL GR","exch":"STU","type":"S","exchDisp":"Stuttgart","typeDisp":"Equity"},{"symbol":"ZAG.SW","name":"ZUMTOBEL GR","exch":"EBS","type":"S","exchDisp":"Swiss","typeDisp":"Equity"},{"symbol":"T9Z.DU","name":"ZUMTOBEL GR","exch":"DUS","type":"S","exchDisp":"Dusseldorf Stock Exchange ","typeDisp":"Equity"},{"symbol":"T9Z.MU","name":"ZUMTOBEL GR","exch":"MUN","type":"S","exchDisp":"Munich","typeDisp":"Equity"},{"symbol":"ZMTBF.PK","name":"ZUMTOBEL AG","exch":"PNK","type":"S","exchDisp":"OTC Markets","typeDisp":"Equity"},{"symbol":"T9Z.F","name":"ZUMTOBEL GR","exch":"FRA","type":"S","exchDisp":"Frankfurt","typeDisp":"Equity"},{"symbol":"0MJH.L","name":"Zumtobel Group AG","exch":"LSE","type":"S","exchDisp":"London","typeDisp":"Equity"},{"symbol":"T9Z.HM","name":"ZUMTOBEL GR","exch":"HAM","type":"S","exchDisp":"Hamburg","typeDisp":"Equity"}]}})

查询的字符串位于会话变量 Session["sSearch"] 内。我正在使用Newtonsoft的 Json.NET。我的代码隐藏文件如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Data;
public partial class DepotStockSearch : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Get Stock Data
        int iStockCount;
        string sSearch = Session["sSearch"].ToString();
        string sYahooUrl = "http://autoc.finance.yahoo.com/autoc?query=" + sSearch + "&callback=YAHOO.Finance.SymbolSuggest.ssCallback";
        try
        {
            WebClient WebC = new WebClient();
            string sData = WebC.DownloadString(sYahooUrl);
            JObject joJSON = JObject.Parse(sData);
            iStockCount = joJSON["ResultSet"]["Result"].Count();
            testlabel.Text = iStockCount.ToString(); //Test
            string[,] arr_sQuery = new string[iStockCount, 3];
            if (iStockCount > 0)
            {
                string sSymbol = null;
                string sCompany = null;
                string sExchange = null;
                for (int iCount = 0; iCount < iStockCount; iCount++)
                {
                    JToken jtSymbol = joJSON["ResultSet"]["Result"][iStockCount]["symbol"];
                    JToken jtCompany = joJSON["ResultSet"]["Result"][iStockCount]["name"];
                    JToken jtExchange = joJSON["ResultSet"]["Result"][iStockCount]["exchDisp"];
                    int iParameter = 1;
                    switch (iParameter)
                    {
                        case 0:
                            sSymbol = Methods.JTokenReader(jtSymbol);
                            iParameter++;
                            break;
                        case 1:
                            sCompany = Methods.JTokenReader(jtCompany);
                            iParameter++;
                            break;
                        case 2:
                            sExchange = Methods.JTokenReader(jtExchange);
                            break;
                    }
                    string sArrayValue = null;                    
                    for (int iCount2 = 0; iCount2 < 3; iCount2++)
                    {
                        switch (iCount2)
                        {
                            case 0:
                                sArrayValue = sSymbol;
                                break;
                            case 1:
                                sArrayValue =sCompany;
                                break;
                            case 2:
                                sArrayValue = sExchange;
                                break;
                        }
                        arr_sQuery[iCount,iCount2] = sArrayValue; //Write Stock Data into array
                    }
                }
            }
            else
            {
                //Error
            }
            //Send data to table
            DataTable dtQueryResults = new DataTable();
            dtQueryResults.Columns.Add("Symbol", Type.GetType("System.String"));
            dtQueryResults.Columns.Add("Company", Type.GetType("System.String"));
            dtQueryResults.Columns.Add("Exchange", Type.GetType("System.String"));
            for (int iCount3 = 0; iCount3 < iStockCount; iCount3++)
            {
                dtQueryResults.Rows.Add();
                dtQueryResults.Rows[dtQueryResults.Rows.Count - 1]["Symbol"] = arr_sQuery[iCount3, 0];
                dtQueryResults.Rows[dtQueryResults.Rows.Count - 1]["Company"] = arr_sQuery[iCount3, 1];
                dtQueryResults.Rows[dtQueryResults.Rows.Count - 1]["Exchange"] = arr_sQuery[iCount3, 2];
            }
            QueryTable.DataSource = dtQueryResults;
            QueryTable.DataBind();
        }
        catch(Exception ex)
        {
        }
    } //PageLoad end
}

HTML 如下所示:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DepotStockSearch.aspx.cs" Inherits="DepotStockSearch" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <link rel="stylesheet" href="stylesheets/default.css" />
    <link rel="shortcut icon" href="pictures/icon.png"/>
    <link href="http://fonts.googleapis.com/css?family=Raleway:400,200,500,600,700,800,300" rel="stylesheet" />
    <title>ASP .NET Aktiendepot</title>
</head>
<body>
<form runat="server">
    <asp:GridView ID="QueryTable" runat="server" AutoGenerateColumns = "false" AlternatingRowStyle-BackColor = "#C2D69B" 
     AllowPaging ="true" PageSize = "50" Caption = "Results">
         <Columns>
             <asp:BoundField ItemStyle-Width = "150px"
              DataField = "Symbol" HeaderText = "Symbol" />
             <asp:BoundField ItemStyle-Width = "150px"
              DataField = "Company" HeaderText = "Company" />
             <asp:BoundField ItemStyle-Width = "150px"
              DataField = "Exchange" HeaderText = "Exchange" />
        </Columns>
    </asp:GridView>
</form>
</body>
</html>

我认为 JSON 转换的某些内容无法正常工作。当我运行它时,错误 JsonReaderException 未处理:解析值时遇到意外字符:Y。 路径 '',第 0 行,位置 0。如果有人能帮助我,我将不胜感激。

问候奥兰多

这不是有效的"纯"JSON,开头的YAHOO.Finance.SymbolSuggest.ssCallback(和结尾的)需要去掉。JSON 对象应以 { 开头,以 } 结尾;一个数组,[].有关 JSON 的(非常简单的)语法的说明,请参阅 json.org。

因此,如果您有

    const string yahooPrefix = "YAHOO.Finance.SymbolSuggest.ssCallback(";
    const string yahooPostfix = ")";

你会做的

        sData = sData.Trim();
        if (sData.StartsWith(yahooPrefix) && sData.EndsWith(yahooPostfix))
        {
            sData = sData.Substring(yahooPrefix.Length, sData.Length - yahooPostfix.Length - yahooPrefix.Length);
        }
        JObject joJSON = JObject.Parse(sData);

相关内容

  • 没有找到相关文章

最新更新