使用org.JSON解析JSON以获取Java中重复数据字段的第一个实例

时间:2018-09-29 22:24:11

标签: java json parsing org.json

我正在尝试从以下JSON文件中解析“ actualEPS​​”的第一个实例:

   {"symbol":"AAPL","earnings":[{"actualEPS":2.34,"consensusEPS":2.17,"estimatedEPS":2.17,"announceTime":"AMC","numberOfEstimates":10,"EPSSurpriseDollar":0.17,"EPSReportDate":"2018-07-31","fiscalPeriod":"Q3 2018","fiscalEndDate":"2018-06-30","yearAgo":1.67,"yearAgoChangePercent":0.40119760479041916,"estimatedChangePercent":0.29940119760479045,"symbolId":11},{"actualEPS":2.73,"consensusEPS":2.69,...}

这是当前的方法。我知道我正在从目标获取数据,因为我可以对字符串“ inputLine”进行Sysout并查看完整文件。从这一点上我很难解析。我已经安装并导入了org.JSON库。

    public static void getData(String s) throws Exception {
    String urlBase = new String(theWebSiteImGettingDataFrom)
    URL targetURL = new URL(urlBase);
    URLConnection yc = targetURL.openConnection();
    BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                            yc.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null) { 

        System.out.println(inputLine);
    } // end while

    in.close();

    JSONObject obj = new JSONObject(inputLine);
    double eps = obj.getJSONObject("earnings").getDouble("actualEPS");

    System.out.println("This is the first instance of EPS: " + eps);

} // end getData method

我在堆栈跟踪中得到了一个空指针异常:

    at org.json.JSONTokener.<init>(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:357)
at code.URLConnectionReader.getData(URLConnectionReader.java:39)

如何解析“ actualEPS​​”的第一个实例的数据,而仅解析第一个实例的数据?

编辑

    JSONObject obj = new JSONObject(inputLine);
    JSONArray earningsArray = obj.getJSONArray("earnings");
    JSONObject firstEPS = earningsArray.getJSONObject(0);
    double eps = firstEPS.getDouble("actualEPS");

    System.out.println("This is the first instance of EPS: " + eps);

1 个答案:

答案 0 :(得分:0)

首先,由于我不知道您的json有多大,并且您只想解析json本身的特定部分,因此建议您使用 JsonReader.class 而不是 JsonObject.class

简短区别:

  • JsonObject将整个json解析到RAM中,并且需要小于1 MB。
  • JsonReader使用流方法,使您可以更有效地处理大型json。

第二,如果您知道您始终只需要json的第一个实例,则可以在解析它之前简单地缩短jsonString本身(例如substring等)。


现在输入您的代码:

  

公共静态void getData(String s)引发异常{       字符串urlBase =新字符串(theWebSiteImGettingDataFrom); //分号!       URL targetURL =新URL(urlBase);       URLConnection yc = targetURL.openConnection();       BufferedReader in = new BufferedReader(                               新的InputStreamReader(                               yc.getInputStream()));       字符串inputLine;

while ((inputLine = in.readLine()) != null) { 

    System.out.println(inputLine);
} // end while

in.close();

System.out.println("My json: "+inputLine); //TODO: What is your output here?  

JSONObject obj = new JSONObject(inputLine);
double eps = obj.getJSONObject("earnings").getDouble("actualEPS");

System.out.println("This is the first instance of EPS: " + eps);
     

} //结束getData方法

请发表评论,因为我无法确定您是否从服务器获取json。


编辑: 您的错误在以下行中:

double eps = obj.getJSONObject("earnings").getDouble("actualEPS");

简而言之,应该是这样的:

double eps = obj.getJSONArray("earnings").getJSONObject(0).getDouble("actualEPS");

但是,为什么呢?您的属性收入返回一个JSONArray(这意味着您有多个带有indizes的行)。因此,您不应该只将“收益”作为JSONObject,而应该将其用作JSONArray,然后提取第一行(= .getJSONObject(0))。提取第一行后,您实际上可以使用double-Value。

我希望这能奏效:)


第二次修改: 改变那个..

  

while(((inputLine = in.readLine())!= null){

System.out.println(inputLine); } // end while

至:

  

while(((inputLine + = in.readLine())!= null){

System.out.println(inputLine); } // end while

您的while循环不断迭代直到 .readLine()返回 null 。 由于null是最后一次迭代,因此变量中只有null。

根据建议,您可以通过简单地将 =更改为+ = 来解决此问题。

我希望我们现在就知道了。 :)