Johnny  S
Johnny S

Reputation: 37

.keys() method not working on JSONObject eclipse

i am trying to use the .keys() method to get the name of JSON Object's the code im using is;

Iterator<String> keys = JSONObject.keys();

.keys() is underelined as red on eclipse, i dont know why, can any one help, thanks! -

enter image description here

I have JSON simple as an external library and have imported it, not sure what else to do

EDIT:

Here is more code;

    JSONParser parser = new JSONParser();
            FileReader testfile = new FileReader("test2.txt");
            Object obj = parser.parse(testfile); 
            JSONObject jsonObject = (JSONObject) obj;
            JSONObject name = (JSONObject) jsonObject.get("txt");
            String time = (String) name.get("name");
            JSONObject example2 = (JSONObject) jsonObject.get("birth");
            System.out.println(example2);



        Iterator keys = example2 .keys(); <-- where the red line shows up

Second edit: here are my imports.

 import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
     import org.json.simple.parser.ParseException;

Upvotes: 0

Views: 2022

Answers (2)

spi
spi

Reputation: 1735

With this artifact: https://mvnrepository.com/artifact/org.json/json/20170516

Use the following code:

JSONObject obj = new JSONObject("{\"key\":\"value\"}");
for(Object o : obj.keys()) { ... }

It will work.

Do not mix API.

Upvotes: 0

light_303
light_303

Reputation: 2111

try:

  Iterator<String> keys = example2.keySet().iterator();

Upvotes: 2

Related Questions