使用GSON从URL解析JSON到Array

时间:2013-04-10 06:18:06

标签: java json yql

晚上好,

我希望通过YQL请求将我从yahoo.finance.quote获得的JSON块解析为一个与SQL DB一起使用的列表。

以下是相关的代码块:

String uri = "(\"GOOG\",\"YHOO\",\"AAPL\",\"C\",\"FB\",\"GE\",\"BAC\")";

String yql = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20" + uri + "&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";  


        BufferedReader reader = null;
            URL url = new URL(yql);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));

            Class1 data = gson.fromJson(reader, Class1.class);
            System.out.println(new Gson().toJson(data));

public class Class1 {
      private int query;
      private int results;
      private List<Class2> quote;
    }

    public class Class2 {
      private String Name;
    }

我想从JSON获得的实际数据是Data.Query.Result.Quote,但我似乎无法使用内部类(Class1,Class2)正确引用它。任何人都可以提供一些帮助,或者让我知道我是否在做些傻事?谢谢。

1 个答案:

答案 0 :(得分:0)

Queryresultsquote本身就是JSONObject。你不能用这种方式映射它们并期望它能够工作。使用此结构作为参考并完成其余部分。

解析

Response fromJson = gson.fromJson(file, Response.class);
System.out.println(fromJson.getQuery().getResults().getQuote().getSymbol());

输出

  

结构

public class Response
{
    private Query query;

    public Query getQuery()
    {
        return query;
    }

    public void setQuery(Query query)
    {
        this.query = query;
    }

}

class Query 
{
    private int count;
    private Results results;
    public int getCount()
    {
        return count;
    }
    public void setCount(int count)
    {
        this.count = count;
    }
    public Results getResults()
    {
        return results;
    }
    public void setResults(Results results)
    {
        this.results = results;
    }


}

class Results
{
    private Quote quote;

    public Quote getQuote()
    {
        return quote;
    }

    public void setQuote(Quote quote)
    {
        this.quote = quote;
    }


}

class Quote
{
    private String symbol;

    public String getSymbol()
    {
        return symbol;
    }

    public void setSymbol(String symbol)
    {
        this.symbol = symbol;
    }
}