将字符串读入Json



我正在尝试使用以下代码将字符串读取为json:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
  string final =" quoteDataObj : [{"symbol":"@CL.1","symbolType":"symbol","code":0,"name":"WTI Crude Oil (Sepu002715)","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:UsersidfDocumentsVisual Studio 2012ProjectsScreenScrapeScreenScrapeProgram.cs:line 519
   at ConsoleApplication276.Program.Main(String[] args) in c:UsersidfDocumentsVisual Studio 2012ProjectsScreenScrapeScreenScrapeProgram.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中这是有效的

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'quoteDataObjs=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

字符串看起来像这样raw

[{"symbol":"@CL.1","symbolType":"symbol","code":0,"name":"WTI Crude Oil (Sepu002715)","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 (Sepu002715)','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:UsersidfDocumentsVisual Studio 2012ProjectsScreenScrapeScreenScrapeProgram.cs:line 586
   at ConsoleApplication276.Program.Main(String[] args) in c:UsersidfDocumentsVisual Studio 2012ProjectsScreenScrapeScreenScrapeProgram.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很擅长这个。在','上分割字符串可能更容易,然后在':'上再次分割,将其读入Dictionary

编辑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 = @"quoteDataObjs=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);
                }                                   
          }
     }

这样使用

var json = "[{"symbol":"@CL.1","symbolType":"symbol","code":0,"name":"WTI Crude Oil(Sepu002715)","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; }
}
编辑:

在您的编辑中,您使用'提供新的字符串。现在你可以试试

var json = @"[{'symbol':'@CL.1','symbolType':'symbol','code':0,'name':'WTI Crude Oil (Sepu002715)','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'}]";
var dynObj = JsonConvert.DeserializeObject<List<Foo>>(json);    
foreach (var data in dynObj)
{
    Console.WriteLine(data.AltSymbol);
    Console.WriteLine(data.AssetType);
    Console.WriteLine(data.Change);
    Console.WriteLine(data.Code);
    //... and more ...
}
Console.ReadKey();

可以将"替换为'。示例:

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

相关内容

  • 没有找到相关文章

最新更新