试图读取URL的json文件

时间:2018-11-20 06:29:42

标签: java

我有这个java文件:

const data = [{"id":"2", "weeks":2}, {"id":"2", "weeks":4}, {"id":3, "weeks":7}],
      result = Object.values(data.reduce((r,{id,weeks}) => {
        r[id] = r[id] || {id, weeks : 0};
        r[id].weeks += weeks;
        return r;
      },{}));
console.log(result);

我从这里借来的代码: https://www.oracle.com/technetwork/articles/java/json-1973242.html

我只是尝试尝试从给定的url读取json数组(该url是实时有效的,只需放在浏览器中即可查看)。

我相信org.json.simple。*的jar文件位于以下位置:

我试图在不使用Maven的情况下进行构建,直到我尝试导入org.json.simple jar为止,它都运行良好:

package foo;

import java.net.*;
import java.io.*;
import org.json.simple.*;


class JsonObject {
  String foo;
}

public class Bar {

    public static void main(String[] args){

        URL url = new URL("https://raw.githubusercontent.com/oresoftware/oredoc/master/test/builds/java/one/test.json");
        try (InputStream is = url.openStream();
        JsonReader rdr = Json.createReader(is)) {

                 JsonObject obj = rdr.readObject();
                 JsonArray results = obj.getJsonArray("data");
                 for (JsonObject result : results.getValuesAs(JsonObject.class)) {
                       System.out.print(result.getJsonObject("from").getString("name"));
                       System.out.println(result.getString("message", ""));

                     }
             }

    }
}

我唯一的猜测是我使用的CLASSPATH env变量错误,但出现此错误:

#!/usr/bin/env bash

dir="$(dirname ${BASH_SOURCE})";
export CLASSPATH="${CLASSPATH}:$dir/foo/java-json.jar"

javac "$dir/foo/"*.java

jar -c -m "$dir/foo/manifest.mf" -f foo.jar "$dir/foo/"*.class

java -jar "$dir/foo.jar"

第一行说./test/builds/java/one/foo/Bar.java:5: error: package org.json.simple does not exist import org.json.simple.*; ^ ./test/builds/java/one/foo/Bar.java:22: error: cannot find symbol JsonReader rdr = Json.createReader(is)) { ^ symbol: class JsonReader location: class Bar ./test/builds/java/one/foo/Bar.java:22: error: cannot find symbol JsonReader rdr = Json.createReader(is)) { ^ symbol: variable Json location: class Bar ./test/builds/java/one/foo/Bar.java:25: error: cannot find symbol JsonArray results = obj.getJsonArray("data"); ^ symbol: class JsonArray location: class Bar ./test/builds/java/one/foo/Bar.java:25: error: cannot find symbol JsonArray results = obj.getJsonArray("data"); ^ symbol: method getJsonArray(String) location: variable obj of type JsonObject ./test/builds/java/one/foo/Bar.java:27: error: cannot find symbol System.out.print(result.getJsonObject("from").getString("name")); ^ symbol: method getJsonObject(String) location: variable result of type JsonObject ./test/builds/java/one/foo/Bar.java:29: error: cannot find symbol System.out.println(result.getString("message", "")); ^ symbol: method getString(String,String) location: variable result of type JsonObject 7 errors 包不存在,所以我是否要告诉Java命令关于那个jar文件的信息?就我所知,CLASSPATH env var是正确的!

1 个答案:

答案 0 :(得分:2)

正如您所说,问题在于软件包不存在。

  1. 将org.json.simple软件包移动到已编译的jar文件夹中。
  2. 运行jar。