更改响应字符串后JSON反序列化无法工作

本文关键字:反序列化 工作 JSON 响应 字符串 | 更新日期: 2023-09-27 18:26:14

我想反序列化以下字符串:

YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"google","Result":[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GGQ1.DE","name": "GOOGLE-A","exch": "GER","type": "S","exchDisp":"XETRA","typeDisp":"Equity"}]}})

我用WebClient下载。但在反序列化之前,我需要删除末尾的"YAHOO.Finance.SymbolSuggest.ssCallback("answers")":

// get response
WebResponse response = request.EndGetResponse(result);
Stream stream = response.GetResponseStream();
// convert to string
StreamReader reader = new StreamReader(stream);
string output = reader.ReadToEnd();
// cut string
output = output.Substring(39, output.Length - 40);
// convert back to stream
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(output));

所以,我得到的回应是一股洪流。我将该流转换为字符串,更改字符串,然后将字符串转换回流。接下来,我尝试反序列化:

// parse json
System.Runtime.Serialization.Json.DataContractJsonSerializer rootSer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(RootObject));
// get root object
RootObject root = (RootObject)rootSer.ReadObject(ms);
// add to listbox
foreach (Result res in root.ResultSet.Result)
{
    Dispatcher.BeginInvoke(() => ResultList.Add(res));
}

问题是我在foreach中得到了一个nullpointexeption。。。我的课程是这样的:

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; }
}

更改响应字符串后JSON反序列化无法工作

您可以使用Regex从jsonp 中提取json

output = Regex.Match(output, @".+?'((.+?)')").Groups[1].Value