【问题标题】:Unable to execute Java program with Json-simple jar file无法使用 Json-simple jar 文件执行 Java 程序
【发布时间】:2017-04-02 20:11:18
【问题描述】:

我正在尝试编写一个将 JSON 数据写入文件的简单 Java 程序。我正在使用 JSON 简单 jar 文件对其进行编译,但出现错误。以下是我所做的:

//JsonSimpleWriteExample.java

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

import java.io.FileWriter;
import java.io.IOException;

public class JsonSimpleWriteExample {

public static void main(String[] args) {

    JSONObject obj = new JSONObject();
    obj.put("name", "mkyong.com");
    obj.put("age", new Integer(100));

    JSONArray list = new JSONArray();
    list.add("msg 1");
    list.add("msg 2");
    list.add("msg 3");

    obj.put("messages", list);

    try (FileWriter file = new FileWriter("f:\\test.json")) {

        file.write(obj.toJSONString());
        file.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.print(obj);

  }

 }

要在终端中编译上述程序,我正在做:

javac -cp json-simple-1.1.1.jar JsonSimpleWriteExample.java

我从http://www.java2s.com/Code/Jar/j/json-simple.htm下载了json-simple-1.1.1.jar文件

我收到以下错误:

Note: JsonSimpleWriteExample.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

我正在使用 MacOS。谁能帮我解决这个问题。

当我尝试运行我的类文件时,出现以下错误:

$ java JsonSimpleWriteExample

我得到的错误:

  Exception in thread "main" java.lang.NoClassDefFoundError: org/json/simple/JSONObject
at JsonSimpleWriteExample.main(JsonSimpleWriteExample.java:11)
  Caused by: java.lang.ClassNotFoundException: org.json.simple.JSONObject
  at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
  at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
  ... 1 more

【问题讨论】:

  • 这看起来不像是错误,而是警告。错误会阻止我们编译,警告会告诉我们潜在的问题。原始类型就是其中之一。您被告知编译器无法在类型安全方面为您提供帮助。但是编译器应该能够生成.class 文件,因此您应该能够运行此代码(如果您在没有编译器帮助的情况下搞砸了,您可能会遇到一些异常警告 i> 关于)
  • 您需要使用 -cp json-simple 将 jar 包含在类路径中......
  • @efekctive 我准备在创建 cass 文件时这样做:javac -cp json-simple-1.1.1.jar JsonSimpleWriteExample.java
  • 编译与运行无关

标签: java json macos terminal


【解决方案1】:

如你所愿,你使用外部 jar 文件进行编译,以便编译器在编译期间找到你使用的符号。

javac -cp json-simple-1.1.1.jar JsonSimpleWriteExample.java

在运行时也必须这样做:

java JsonSimpleWriteExample -cp ./json-simple-1.1.1.jar

在您的示例中,这是输出:

{"name":"mkyong.com","messages":["msg 1","msg 2","msg 3"],"age":100}

正如@Pshemo 所说,您得到的那些“错误”实际上是警告。您可以查看更多关于未经检查或不安全的操作here 和here。

【讨论】:

    【解决方案2】:
    import org.json.simple.JSONObject;
    
    JSONObject jsonObject = (JSONObject) yourOrginalObject;
    
    //code for get all keys from json
    Set<String> keys=jsonObject.keySet();
    
    //iterate the keys
    
    //get values by passing keys
    jsonObject.get(pass individual keys);
    

    【讨论】:

      猜你喜欢
      • 2011-06-23
      • 1970-01-01
      • 2012-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      相关资源
      最近更新 更多