以下代码显示:
JavaApplication1.java:34: error: non-static method get(Object) cannot be referenced from a static context JSONArray cars = (JSONArray) JSONObject.get("cars");
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JavaApplication1 {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("C:/Users/Glambert/Dropbox/java/New folder/perfection/UPdate/json.txt"));
for (Object o : a)
{
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
JSONArray cars = (JSONArray) JSONObject.get("cars");
for (Object c : cars)
{
System.out.println(c+"");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
任何人都知道为什么会这样?
(顺便说一下,这个代码是在网上找到的,我编辑它来测试运行,这样我就可以创建一个新的代码来接收不同类型的txt文件。)
项目:来自StackOverflow页面How to read json file into java with simple JSON library
的代码答案 0 :(得分:1)
检查此行
JSONArray cars = (JSONArray) JSONObject.get("cars");
用
更改它 JSONArray cars = (JSONArray) person.get("cars");
问题是因为你直接在类上调用了get方法。