简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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