简体   繁体   English

使用GSON从URL将JSON解析为数组

[英]Parse JSON to Array from URL using GSON

Good evening, 晚上好,

I'm looking to parse a JSON block I get from yahoo.finance.quote through a YQL request into a list to be used with a SQL DB. 我正在寻找将通过yahoo.finance.quote通过YQL请求从JSON块中获取的JSON块解析为与SQL DB一起使用的列表。

Here is the relevant block of code: 这是相关的代码块:

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

The actual data I want from the JSON is Data.Query.Result.Quote, but I cannot seem to reference this properly using Inner Classes (Class1, Class2). 我想从JSON获得的实际数据是Data.Query.Result.Quote,但是我似乎无法使用内部类(Class1,Class2)正确地引用它。 Could anyone provide some assistance, or let me know if I'm doing something silly? 谁能提供帮助,或者让我知道我是否在做傻事? Thank you. 谢谢。

Query , results and quote are JSONObject s in their own right. Queryresultsquote本身就是JSONObject You cannot map them this way and expect it to work. 您无法以这种方式映射它们并期望它能正常工作。 Use this structure as a reference and complete the rest. 使用此结构作为参考,并完成其余部分。

Parse 解析

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

Output 输出量

GOOG 高格

Structure 结构体

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM