0

The code below shows:

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();
        }
    }
}

Anyone has any idea why this is the case?

(by the way, this code was found online and I edited it to test run, so that I can create a new code to take in a different kind of txt file.)

Project: Code from StackOverflow page How to read json file into java with simple JSON library

Code Author: https://stackoverflow.com/users/1212960/greg-kopff

Community
  • 1
  • 1
Ivan Teo
  • 11
  • 4
  • If the code was found on line, you should credit the original author and link to where you found it. – RealSkeptic Oct 29 '15 at 12:54
  • @RealSkeptic Thanks for the notice! Credited! – Ivan Teo Oct 29 '15 at 13:01
  • 1
    Possible duplicate of ["Non-static method cannot be referenced from a static context" error](http://stackoverflow.com/questions/4922145/non-static-method-cannot-be-referenced-from-a-static-context-error) – Jiri Tousek Oct 29 '15 at 13:20

1 Answers1

1

Check this line

 JSONArray cars = (JSONArray) JSONObject.get("cars");

change it with

 JSONArray cars = (JSONArray) person.get("cars");

Issue was since you are calling the get method directly on the class.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
Vivek Singh
  • 2,047
  • 11
  • 24