0

I've read some other questions about this, but they did not seem to help me. As the title says, I want to know how to read from .json files using Java. Eg. I want my program to read a boolean value. (That is what I want it to.)

I really hope you will be able to help me with this. I am able to use json-simple-1.1.1 if needed.

What I've found so far (That did not work):

    String str = "Name";
    JSONObject obj = new JSONObject();
    String n = (String) obj.get("Name");
    if (!n.equals("true")) {

    } else
    if (n.equals("true")) {
        ButtonsShow = true;
    } else if (n.equals("false")) {
        ButtonsShow = false;
    }

Click to view the .Json file

ApplePie
  • 1
  • 1
  • 1
  • 6

1 Answers1

0

you try it:

  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 JsonSimpleExample {
     public static void main(String[] args) {

    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(new FileReader("c:\\test.json"));

        JSONObject jsonObject = (JSONObject) obj;

        String name = (String) jsonObject.get("name");
        System.out.println(name);

        long age = (Long) jsonObject.get("age");
        System.out.println(age);

        // loop array
        JSONArray msg = (JSONArray) jsonObject.get("messages");
        Iterator<String> iterator = msg.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

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

     }

}
Kumaresan Perumal
  • 1,926
  • 2
  • 29
  • 35