C# 将字符串读入Json
我正在尝试使用以下代码将字符串读入json:C# 将字符串读入Json,c#,json,json.net,C#,Json,Json.net,我正在尝试使用以下代码将字符串读入json: using Newtonsoft.Json; using Newtonsoft.Json.Converters; string final =" quoteDataObj : [{"symbol":"@CL.1","symbolType":"symbol","code":0,"name":"WTI Crude Oil (Sep\u002715)","shortName":"OIL","last":"42.14","exchange":"New
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
string final =" quoteDataObj : [{"symbol":"@CL.1","symbolType":"symbol","code":0,"name":"WTI Crude Oil (Sep\u002715)","shortName":"OIL","last":"42.14","exchange":"New York Mercantile Exchange","so
urce":"","open":"42.23","high":"42.26","low":"41.35","change":"-0.09","currencyCode":"USD","timeZone":"EDT","volume":"6526","provider":"CNBC Quote Cache","altSymbol":"CL/U5","curmk
tstatus":"REG_MKT","realTime":"false","assetType":"DERIVATIVE","noStreaming":"false","encodedSymbol":"%40CL.1"}]";
通过调用将其读入Json[Newtonsoft]时
dynamic dynObj = JsonConvert.DeserializeObject(final);
我得到以下例外
{Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: q. Path '', line 0, position 0.
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.JsonTextReader.ReadInternal()
at Newtonsoft.Json.JsonTextReader.Read()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value)
at ConsoleApplication276.Program.GetCNBCQuote(String symbol) in c:\Users\idf\Documents\Visual Studio 2012\Projects\ScreenScrape\ScreenScrape\Program.cs:line 519
at ConsoleApplication276.Program.Main(String[] args) in c:\Users\idf\Documents\Visual Studio 2012\Projects\ScreenScrape\ScreenScrape\Program.cs:line 535
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()}
有趣的是,在python中,这可以工作在fire中
import json
clurl = 'http://data.cnbc.com/quotes/@CL.1'
def wgetUrl(target):
try:
req = urllib2.Request(target)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3')
response = urllib2.urlopen(req)
outtxt = response.read()
response.close()
except:
return ''
return outtxt
def CLLast():
content = wgetUrl(clurl)
matches = re.findall(r'quoteDataObj\s\=\s(\[.+\])', content)
if len(matches) > 0:
list = json.loads(matches[0])
python_dict = list[0]
tupleQuote = (iCL, 0, float(python_dict['last']), 0, float(python_dict['last']), 0, millis)
callback(sCL, tupleQuote)
编辑1
这根绳子看起来像这样粗的
[{"symbol":"@CL.1","symbolType":"symbol","code":0,"name":"WTI Crude Oil (Sep\u002715)","shortName":"OIL","last":"42.10","exchange":"New York Mercantile Exchange","source":"","open"
:"42.23","high":"42.26","low":"41.35","change":"-0.13","currencyCode":"USD","timeZone":"EDT","volume":"7702","provider":"CNBC Quote Cache","altSymbol":"CL/U5","curmktstatus":"REG_M
KT","realTime":"false","assetType":"DERIVATIVE","noStreaming":"false","encodedSymbol":"%40CL.1"}]
然后我用这个代码替换它
final = final.Replace('"', '\'');
所以看起来像这样
[{'symbol':'@CL.1','symbolType':'symbol','code':0,'name':'WTI Crude Oil (Sep\u002715)','shortName':'OIL','last':'42.10','exchange':'New York Mercantile Exchange','source':'','open'
:'42.23','high':'42.26','low':'41.35','change':'-0.13','currencyCode':'USD','timeZone':'EDT','volume':'7832','provider':'CNBC Quote Cache','altSymbol':'CL/U5','curmktstatus':'REG_M
KT','realTime':'false','assetType':'DERIVATIVE','noStreaming':'false','encodedSymbol':'%40CL.1'}]
我走近了,因为现在例外是
{Newtonsoft.Json.JsonReaderException: Additional text encountered after finished reading JSON content: C. Path '', line 2, position 4.
at Newtonsoft.Json.JsonTextReader.ReadInternal()
at Newtonsoft.Json.JsonTextReader.Read()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
at ConsoleApplication276.Program.GetCNBCQuote(String symbol) in c:\Users\idf\Documents\Visual Studio 2012\Projects\ScreenScrape\ScreenScrape\Program.cs:line 586
at ConsoleApplication276.Program.Main(String[] args) in c:\Users\idf\Documents\Visual Studio 2012\Projects\ScreenScrape\ScreenScrape\Program.cs:line 602
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()}
编辑2
我认为json在这方面很在行。只需在“,”上拆分字符串,然后通过在“:”上再次拆分将其读入字典可能会更容易
编辑3
代码如下所示。将“CL.1”作为符号传递
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using System.Windows.Forms;
using System.Net;
using System.Globalization;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.PlatformServices;
using System.Reactive.Linq;
using System.Xml;
using System.Runtime.Serialization;
using HtmlAgilityPack;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class Program
{
// navigate WebBrowser to the list of urls in a loop
public static string DoWorkAsync(string args)
{
Console.WriteLine("Start working.");
using (WebClient wb = new WebClient())
{
wb.Headers["User-Agent"] =
"User-Agent" + "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3";
// Download data.
string html = wb.DownloadString(args);
//Console.WriteLine(html);
Console.WriteLine("End working.");
return html;
}
}
[DataContract]
public class CNBC
{
[DataMember(Name = "symbol")]
public string Symbol { get; set; }
[DataMember(Name = "symbolType")]
public string SymbolType { get; set; }
[DataMember(Name = "code")]
public int Code { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "shortName")]
public string ShortName { get; set; }
[DataMember(Name = "last")]
public string Last { get; set; }
[DataMember(Name = "exchange")]
public string Exchange { get; set; }
[DataMember(Name = "source")]
public string Source { get; set; }
[DataMember(Name = "open")]
public string Open { get; set; }
[DataMember(Name = "high")]
public string High { get; set; }
[DataMember(Name = "low")]
public string Low { get; set; }
[DataMember(Name = "change")]
public string Change { get; set; }
[DataMember(Name = "currencyCode")]
public string CurrencyCode { get; set; }
[DataMember(Name = "timeZone")]
public string TimeZone { get; set; }
[DataMember(Name = "volume")]
public string Volume { get; set; }
[DataMember(Name = "provider")]
public string Provider { get; set; }
[DataMember(Name = "altSymbol")]
public string AltSymbol { get; set; }
[DataMember(Name = "curmktstatus")]
public string Curmktstatus { get; set; }
[DataMember(Name = "realTime")]
public string RealTime { get; set; }
[DataMember(Name = "assetType")]
public string AssetType { get; set; }
[DataMember(Name = "noStreaming")]
public string NoStreaming { get; set; }
[DataMember(Name = "encodedSymbol")]
public string EncodedSymbol { get; set; }
}
public static string GetCNBCQuote(string symbol)
{
string url = "http://data.cnbc.com/quotes/@" + symbol;
string html = DoWorkAsync(url);
string regPattern = @"quoteDataObj\s\=\s(\[.+\])";
//Regex re = new Regex(regPattern);
Match match = Regex.Match(html, regPattern);
if (match.Success)
{
string subs = html.Substring(match.Index);
int startIndex = subs.IndexOf('[');
int endIndex = subs.IndexOf(']');
string final = subs.Substring(startIndex - 1, endIndex + 1);
final = final.TrimEnd();
Console.WriteLine(final);
Console.WriteLine();
final = final.Replace('"', '\'');
Console.WriteLine(final);
//This throws exception
dynamic dynObj = JsonConvert.DeserializeObject<List<CNBC>>(final);
foreach (var data in dynObj.quizlist)
{
Console.WriteLine(data);
}
}
}
使用系统;
使用System.Collections.Generic;
使用系统文本;
使用System.Text.RegularExpressions;
使用系统线程;
使用System.Threading.Tasks;
使用System.Linq;
使用System.Windows.Forms;
Net系统;
利用制度全球化;
使用系统。无功;
使用System.Reactive.Concurrency;
使用系统反应性一次性用品;
使用System.Reactive.PlatformServices;
使用System.Reactive.Linq;
使用System.Xml;
使用System.Runtime.Serialization;
使用HtmlAgilityPack;
使用Newtonsoft.Json;
使用Newtonsoft.Json.Converters;
公共课程
{
//将WebBrowser导航到循环中的URL列表
公共静态字符串DoWorkAsync(字符串参数)
{
Console.WriteLine(“开始工作”);
使用(WebClient wb=new WebClient())
{
wb.Headers[“用户代理”]=
“用户代理”+“Mozilla/5.0(Windows;U;Windows NT 5.1;en GB;rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3”;
//下载数据。
字符串html=wb.DownloadString(args);
//Console.WriteLine(html);
控制台写入线(“结束工作”);
返回html;
}
}
[数据合同]
公共类CNBC
{
[DataMember(Name=“symbol”)]
公共字符串符号{get;set;}
[数据成员(Name=“symbolType”)]
公共字符串符号类型{get;set;}
[DataMember(Name=“code”)]
公共整数代码{get;set;}
[数据成员(Name=“Name”)]
公共字符串名称{get;set;}
[DataMember(Name=“shortName”)]
公共字符串短名称{get;set;}
[数据成员(Name=“last”)]
公共字符串Last{get;set;}
[DataMember(Name=“exchange”)]
公共字符串交换{get;set;}
[DataMember(Name=“source”)]
公共字符串源{get;set;}
[DataMember(Name=“open”)]
公共字符串Open{get;set;}
[DataMember(Name=“high”)]
公共字符串高位{get;set;}
[DataMember(Name=“low”)]
公共字符串低位{get;set;}
[DataMember(Name=“change”)]
公共字符串更改{get;set;}
[DataMember(Name=“currencyCode”)]
公共字符串CurrencyCode{get;set;}
[DataMember(Name=“timeZone”)]
公共字符串时区{get;set;}
[DataMember(Name=“volume”)]
公共字符串卷{get;set;}
[DataMember(Name=“provider”)]
公共字符串提供程序{get;set;}
[数据成员(Name=“altSymbol”)]
公共字符串AltSymbol{get;set;}
[数据成员(Name=“curmktstatus”)]
公共字符串Curmktstatus{get;set;}
[DataMember(Name=“realTime”)]
公共字符串实时{get;set;}
[数据成员(Name=“assetType”)]
公共字符串资产类型{get;set;}
[DataMember(Name=“noStreaming”)]
公共字符串NoStreaming{get;set;}
[DataMember(Name=“encodedSymbol”)]
公共字符串EncodedSymbol{get;set;}
}
公共静态字符串GetCNBCQuote(字符串符号)
{
字符串url=”http://data.cnbc.com/quotes/@“+符号;
字符串html=doworksync(url);
字符串regPattern=@“quoteDataObj\s\=\s(\[.+\])”;
//Regex re=新的Regex(regPattern);
Match=Regex.Match(html,regPattern);
如果(匹配成功)
{
string subs=html.Substring(match.Index);
int startIndex=subs.IndexOf('[');
int endIndex=subs.IndexOf(']');
字符串final=subs.Substring(startIndex-1,endIndex+1);
final=final.TrimEnd();
控制台写入线(最终);
Console.WriteLine();
final=final.Replace(“”,“\”);
控制台写入线(最终);
//这引发了异常
dynamic dynObj=JsonConvert.DeserializeObject(final);
foreach(dynObj.quizlist中的var数据)
{
控制台写入线(数据);
}
}
}
以这种方式使用
var json = "[{\"symbol\":\"@CL.1\",\"symbolType\":\"symbol\",\"code\":0,\"name\":\"WTI Crude Oil(Sep\u002715)\",\"shortName\":\"OIL\",\"last\":\"42.14\",\"exchange\":\"New York Mercantile Exchange\","+
"\"source\":\"\",\"open\":\"42.23\",\"high\":\"42.26\",\"low\":\"41.35\",\"change\":\" - 0.09\",\"currencyCode\":\"USD\",\"timeZone\":\"EDT\",\"volume\":\"6526\","+
"\"provider\":\"CNBC Quote Cache\",\"altSymbol\":\"CL / U5\",\"curmktstatus\":\"REG_MKT\",\"realTime\":\"false\",\"assetType\":\"DERIVATIVE\",\"noStreaming\":\"false\",\"encodedSymbol\":\" % 40CL.1\"}]";
var foo = JsonConvert.DeserializeObject<List<Foo>>(json);
public class Foo
{
[DataMember(Name = "symbol")]
public string Symbol { get; set; }
[DataMember(Name = "symbolType")]
public string SymbolType { get; set; }
[DataMember(Name = "code")]
public int Code { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "shortName")]
public string ShortName { get; set; }
[DataMember(Name = "last")]
public string Last { get; set; }
[DataMember(Name = "exchange")]
public string Exchange { get; set; }
[DataMember(Name = "source")]
public string Source { get; set; }
[DataMember(Name = "open")]
public string Open { get; set; }
[DataMember(Name = "high")]
public string High { get; set; }
[DataMember(Name = "low")]
public string Low { get; set; }
[DataMember(Name = "change")]
public string Change { get; set; }
[DataMember(Name = "currencyCode")]
public string CurrencyCode { get; set; }
[DataMember(Name = "timeZone")]
public string TimeZone { get; set; }
[DataMember(Name = "volume")]
public string Volume { get; set; }
[DataMember(Name = "provider")]
public string Provider { get; set; }
[DataMember(Name = "altSymbol")]
public string AltSymbol { get; set; }
[DataMember(Name = "curmktstatus")]
public string Curmktstatus { get; set; }
[DataMember(Name = "realTime")]
public string RealTime { get; set; }
[DataMember(Name = "assetType")]
public string AssetType { get; set; }
[DataMember(Name = "noStreaming")]
public string NoStreaming { get; set; }
[DataMember(Name = "encodedSymbol")]
public string EncodedSymbol { get; set; }
}
您可以将
“
替换为”
。对于示例:
string final ="[
{
'symbol': '@CL.1',
'symbolType': 'symbol',
'code': 0,
'name': 'WTI Crude Oil (Sep'15)',
'shortName': 'OIL',
'last': '42.14',
'exchange': 'New York Mercantile Exchange',
'source': '',
'open': '42.23',
'high': '42.26',
'low': '41.35',
'change': '-0.09',
'currencyCode': 'USD',
'timeZone': 'EDT',
'volume': '6526',
'provider': 'CNBC Quote Cache',
'altSymbol': 'CL/U5',
'curmktstatus': 'REG_MKT',
'realTime': 'false',
'assetType': 'DERIVATIVE',
'noStreaming': 'false',
'encodedSymbol': '%40CL.1'
}
]";
dynamic foo = JsonConvert.DeserializeObject<List<Foo>>(json);
string final=”[
{
“符号”:“@CL.1”,
'symbolType':'symbol',
“代码”:0,
‘名称’:‘WTI原油(2015年9月)’,
“shortName”:“OIL”,
“最后”:“42.14”,
“交易所”:纽约商品交易所,
“来源”:“,
“开放”:“42.23”,
‘高’:‘42.26’,
‘低’:‘41.35’,
‘更改’:‘-0.09’,
“货币代码”:“美元”,
“时区”:“EDT”,
"卷":"6526",,
“提供者”:“CNBC报价缓存”,
“altSymbol”:“CL/U5”,
“curmktstatus”:“REG_MKT”,
“实时”:“假”,
'资产类型':'衍生',
'鼻孔':'假',
'encodedSymbol':'%40CL.1'
}
]";
动态
string final ="[
{
'symbol': '@CL.1',
'symbolType': 'symbol',
'code': 0,
'name': 'WTI Crude Oil (Sep'15)',
'shortName': 'OIL',
'last': '42.14',
'exchange': 'New York Mercantile Exchange',
'source': '',
'open': '42.23',
'high': '42.26',
'low': '41.35',
'change': '-0.09',
'currencyCode': 'USD',
'timeZone': 'EDT',
'volume': '6526',
'provider': 'CNBC Quote Cache',
'altSymbol': 'CL/U5',
'curmktstatus': 'REG_MKT',
'realTime': 'false',
'assetType': 'DERIVATIVE',
'noStreaming': 'false',
'encodedSymbol': '%40CL.1'
}
]";
dynamic foo = JsonConvert.DeserializeObject<List<Foo>>(json);