2012-02-21 3 views
0

json 파일을 반복하고 yahoo API에서 각 레코드의 제목을 검색하려고합니다. 누군가가 어떻게해야 할 지에 대한 조언을 해줄 수 있습니까? 내 코드는 다음과 같습니다 :C# 자바 역 직렬화 문제

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20query%3D%22sushi%22%20and%20location%3D%22san%20francisco%2C%20ca%22&format=json&diagnostics=true&callback=cbfunc"); 
      HttpWebResponse rep = (HttpWebResponse)req.GetResponse(); 

      StreamReader sr = new StreamReader(rep.GetResponseStream()); 

      string data = sr.ReadToEnd(); 

      //Console.WriteLine(data); 

      var jss = new JavaScriptSerializer(); 
      var dict = jss.Deserialize<Dictionary<string,string>>(data); 
+0

JSON의 모습은 무엇입니까? –

답변

1

yahoo가 반환 한 JSON 구조와 일치하도록 몇 가지 클래스를 디자인 할 수 있습니다. 그렇지 않으면 야후 대신 JSON의 JSONP를 반환하기 때문에 또한 callback=cbfunc 매개 변수를 사용하지 마십시오

using System; 
using System.Net; 
using System.Web.Script.Serialization; 

public class YahooResponse 
{ 
    public Query Query { get; set; } 
} 

public class Query 
{ 
    public Results Results { get; set; } 
} 

public class Results 
{ 
    public Result[] Result { get; set; } 
} 

public class Result 
{ 
    public string Title { get; set; } 
} 

class Program 
{ 
    static void Main() 
    { 
     using (var client = new WebClient()) 
     { 
      var json = client.DownloadString("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20query%3D%22sushi%22%20and%20location%3D%22san%20francisco%2C%20ca%22&format=json&diagnostics=true") 
      var jss = new JavaScriptSerializer(); 
      var result = jss.Deserialize<YahooResponse>(json); 
      foreach (var item in result.Query.Results.Result) 
      { 
       Console.WriteLine(item.Title); 
      } 

     } 
    } 
} 
+0

전 성공하지 못했지만 실제로이 일을 실제로 시도했습니다. 이 일을 할 수 있었습니까? –

+0

@ W.Jackson, 예,이 코드를 테스트 한 결과 완벽하게 정상적으로 작동했습니다. –

+0

+1, 묻는대로 질문에 답합니다. –

0

당신이 클라이언트 측 목적으로 JSON을 사용해야합니까? 그렇지 않은 경우 결과 형식을 xml, format = xml로 변경하고 linq를 xml로 변경하는 것이 좋습니다. 그러면 다음 작업을 수행 할 수 있습니다.

if (tickers.Count() == 0) 
      throw new InvalidOperationException("The list of tickers cannot be empty."); 

     string url = BuildUrl(tickers); 

     WebClient http = new WebClient();    
     string xml = http.DownloadString(url); 

     List<Quote> quotes = new List<Quote>(); 

     XDocument doc = XDocument.Parse(xml); 
     foreach (var el in doc.Descendants("quote")) 
     { 
      if (el.Name == "quote") 
      { 
       quotes.Add(new Quote() 
       { 
        Symbol = el.Element("Symbol").Value,       
        TradeDate = el.Element("TradeDate").Value, 
        DaysLow = el.Element("DaysLow").IsEmpty ? null : (decimal?)el.Element("DaysLow"), 
        DaysHigh = el.Element("DaysHigh").IsEmpty ? null :(decimal?)el.Element("DaysHigh"), 
        YearLow = el.Element("YearLow").IsEmpty ? null : (decimal?)el.Element("YearLow"), 
        YearHigh = el.Element("YearHigh").IsEmpty ? null : (decimal?)el.Element("YearHigh"), 
        DividendShare = el.Element("DividendShare").IsEmpty ? null : (decimal?)el.Element("DividendShare"), 
        Open = el.Element("Open").IsEmpty ? null : (decimal?)el.Element("Open"), 
        PreviousClose = el.Element("PreviousClose").IsEmpty ? null : (decimal?)el.Element("PreviousClose"), 
        ShortRatio = el.Element("ShortRatio").IsEmpty ? null : (decimal?)el.Element("ShortRatio"), 
        OneyrTargetPrice = el.Element("OneyrTargetPrice").IsEmpty ? null : (decimal?)el.Element("OneyrTargetPrice"), 
        DividendYield = el.Element("DividendYield").IsEmpty ? null : (decimal?)el.Element("DividendYield"), 
        Ask = el.Element("Ask").IsEmpty ? null : (decimal?)el.Element("Ask"), 
        Bid = el.Element("Bid").IsEmpty ? null : (decimal?)el.Element("Bid"), 
        AskRealtime = el.Element("AskRealtime").IsEmpty ? null : (decimal?)el.Element("AskRealtime"), 
        BidRealtime = el.Element("BidRealtime").IsEmpty ? null : (decimal?)el.Element("BidRealtime"), 
        BookValue = el.Element("BookValue").IsEmpty ? null : (decimal?)el.Element("BookValue"),         
        PercentChangeFromYearLow = el.Element("PercentChangeFromYearLow").Value, 
        LastTradeRealtimeWithTime = el.Element("LastTradeRealtimeWithTime").Value, 
        PercebtChangeFromYearHigh = el.Element("PercebtChangeFromYearHigh").Value, 
        LastTradeWithTime = el.Element("LastTradeWithTime").Value, 
        LastTradePriceOnly = el.Element("LastTradePriceOnly").Value, 
        Name = el.Element("Name").Value, 
        Notes = el.Element("Notes").Value, 
        LastTradeTime = el.Element("LastTradeTime").Value, 
        TickerTrend = el.Element("TickerTrend").Value, 
        StockExchange = el.Element("StockExchange").Value, 
        PercentChange = el.Element("PercentChange").Value, 
        AverageDailyVolume = (Int64?)el.Element("AverageDailyVolume"), 
        Change_PercentChange = el.Element("Change_PercentChange").Value, 
        Change = el.Element("Change").Value, 
        Commission = el.Element("Commission").Value, 
        ChangeRealtime = el.Element("ChangeRealtime").Value, 
        LastTradeDate = el.Element("LastTradeDate").Value 
       }); 
      } 
     } 

     return quotes;