Quel est le meilleur moyen de charger un JSONObject à partir d’un fichier texte json?

Quel serait le moyen le plus simple de charger un fichier contenant JSON dans un JSONObject.

En ce moment, j’utilise json-lib.

C’est ce que j’ai, mais cela jette une exception:

XMLSerializer xml = new XMLSerializer(); JSON json = xml.readFromFile("samples/sample7.json”); //line 507 System.out.println(json.toSsortingng(2)); 

La sortie est:

 Exception in thread "main" java.lang.NullPointerException at java.io.Reader.(Reader.java:61) at java.io.InputStreamReader.(InputStreamReader.java:55) at net.sf.json.xml.XMLSerializer.readFromStream(XMLSerializer.java:386) at net.sf.json.xml.XMLSerializer.readFromFile(XMLSerializer.java:370) at corebus.test.deprecated.TestMain.main(TestMain.java:507) 

essaye ça:

 import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; import org.apache.commons.io.IOUtils; public class JsonParsing { public static void main(Ssortingng[] args) throws Exception { InputStream is = JsonParsing.class.getResourceAsStream( "sample-json.txt"); Ssortingng jsonTxt = IOUtils.toSsortingng( is ); JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt ); double coolness = json.getDouble( "coolness" ); int altitude = json.getInt( "altitude" ); JSONObject pilot = json.getJSONObject("pilot"); Ssortingng firstName = pilot.getSsortingng("firstName"); Ssortingng lastName = pilot.getSsortingng("lastName"); System.out.println( "Coolness: " + coolness ); System.out.println( "Altitude: " + altitude ); System.out.println( "Pilot: " + lastName ); } } 

et ceci est votre sample-json.txt, devrait être au format json

 { 'foo':'bar', 'coolness':2.0, 'altitude':39000, 'pilot': { 'firstName':'Buzz', 'lastName':'Aldrin' }, 'mission':'apollo 11' } 

Merci @Kit Ho pour votre réponse. J’ai utilisé votre code et constaté que je continuais à courir dans des erreurs où mon InputStream était toujours nul et les exceptions ClassNotFound lors de la création de JSONObject. Voici ma version de votre code qui fait l’affaire pour moi:

 import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.json.JSONObject; public class JSONParsing { public static void main(Ssortingng[] args) throws Exception { File f = new File("file.json"); if (f.exists()){ InputStream is = new FileInputStream("file.json"); Ssortingng jsonTxt = IOUtils.toSsortingng(is, "UTF-8"); System.out.println(jsonTxt); JSONObject json = new JSONObject(jsonTxt); Ssortingng a = json.getSsortingng("1000"); System.out.println(a); } } } 

J’ai trouvé cette réponse éclairante sur la différence entre FileInputStream et getResourceAsStream . J’espère que cela aide aussi quelqu’un d’autre.

Avec java 8, vous pouvez essayer ceci:

 import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class JSONUtil { public static JSONObject parseJSONFile(Ssortingng filename) throws JSONException, IOException { Ssortingng content = new Ssortingng(Files.readAllBytes(Paths.get(filename))); return new JSONObject(content); } public static void main(Ssortingng[] args) throws IOException, JSONException { Ssortingng filename = "path/to/file/abc.json"; JSONObject jsonObject = parseJSONFile(filename); //do anything you want with jsonObject } } 

Une autre façon de faire la même chose pourrait être d’utiliser la classe Gson

 Ssortingng filename = "path/to/file/abc.json"; Gson gson = new Gson(); JsonReader reader = new JsonReader(new FileReader(filename)); SampleClass data = gson.fromJson(reader, SampleClass.class); 

Cela donnera un object obtenu après avoir analysé la chaîne json avec laquelle travailler.