简体   繁体   中英

How can I parse this JSON and not get an exception?

I have the following JSON:

    [
  {
    "outcome": "Success",
    "message": "",
    "identity": "",
    "delay": "0",
    "symbol": "AAPL",
    "companyname": "Apple Inc.",
    "date": "Jun 08",
    "time": " 4:52 PM EDT",
    "open": "330.88",
    "close": "332",
    "previousclose": "332.04",
    "high": "334.8",
    "low": "330.51",
    "last": "332",
    "change": "-0.04",
    "percentchange": "-0.012",
    "volume": "1239421",
    "created_at": "1307581193"
  },
  {
    "outcome": "Success",
    "message": "",
    "identity": "",
    "delay": "0",
    "symbol": "GOOG",
    "companyname": "Google Inc.",
    "date": "Jun 08",
    "time": " 3:59 PM EDT",
    "open": "516.76",
    "close": "519.28",
    "previousclose": "519.03",
    "high": "521.14",
    "low": "515.79",
    "last": "519.28",
    "change": "0.25",
    "percentchange": "0.048",
    "volume": "229886",
    "created_at": "1307576900"
  }
]

Here is my Java:

JSONArray jquotes = new JSONArray(json.toString());
                    if (jquotes.length() > 0) {
                        for (int i = 0; i < jquotes.length(); i++) {

                            JSONObject quote = jquotes.getJSONObject(i);

                            Quote myQuote = new Quote();
                            myQuote.setName(quote.getString("companyname"));
                            myQuote.setSymbol(quote.getString("symbol"));
                            myQuote.setLastTradePriceOnly(quote.getString("last"));
                            myQuote.setChange(quote.getString("change"));
                            myQuote.setPercentChange(quote.getString("percentchange"));

                            quotesAdapter.add(myQuote);
                        }
                    }

I am getting the exception:

value of type org.json.JSONArray cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:107)

What you have is actually a JSONArray (notice the brackets at the beginning), so:

JSONArray array = new JSONArray (jsonString);
JSONObject obj = array.getJSONObject(0);
String outcome = obj.getString("outcome");
int delay = getInt("delay");
// etc.

The API is fairly simple. You can read the details here .

As the contents of the question currently stand, the provided JSON deserializes without error with the provided code.

For the working code below, all I did was copy and paste what's in the question, and it runs as expected.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    String jsonInput = readJsonInput(new File("input.json"));
    JSONArray jquotes = new JSONArray(jsonInput);
    int length = jquotes.length();
    List<Quote> quotes = new ArrayList<Quote>(length);
    if (length > 0)
    {
      for (int i = 0; i < length; i++)
      {
        JSONObject quote = jquotes.getJSONObject(i);

        Quote myQuote = new Quote();
        myQuote.setName(quote.getString("companyname"));
        myQuote.setSymbol(quote.getString("symbol"));
        myQuote.setLastTradePriceOnly(quote.getString("last"));
        myQuote.setChange(quote.getString("change"));
        myQuote.setPercentChange(quote.getString("percentchange"));

        quotes.add(myQuote);
      }
    }
    System.out.println(quotes);
  }

  private static String readJsonInput(File inputFile) throws Exception
  {
    StringBuilder result = new StringBuilder();
    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    for (String line = null; (line = reader.readLine()) != null;)
    {
      result.append(line);
    }
    return result.toString();
  }
}

class Quote
{
  private String name;
  private String percentChange;
  private String change;
  private String lastTradePriceOnly;
  private String symbol;

  void setName(String name)
  {
    this.name = name;
  }

  void setPercentChange(String percentChange)
  {
    this.percentChange = percentChange;
  }

  void setChange(String change)
  {
    this.change = change;
  }

  void setLastTradePriceOnly(String lastTradePriceOnly)
  {
    this.lastTradePriceOnly = lastTradePriceOnly;
  }

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

  @Override
  public String toString()
  {
    return String.format(
        "{Quote: name=%s, percentChange=%s, change=%s, lastTradePriceOnly=%s, symbol=%s}",
        name, percentChange, change, lastTradePriceOnly, 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