Quelle est la meilleure façon 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 il lève une exception:

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

La sortie est:

Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(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)
26
demandé sur Larry 2011-09-18 22:20:14

4 réponses

Essayez ceci:

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils; 

    public class JsonParsing {

        public static void main(String[] args) throws Exception {
            InputStream is = 
                    JsonParsing.class.getResourceAsStream( "sample-json.txt");
            String jsonTxt = IOUtils.toString( is );

            JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );        
            double coolness = json.getDouble( "coolness" );
            int altitude = json.getInt( "altitude" );
            JSONObject pilot = json.getJSONObject("pilot");
            String firstName = pilot.getString("firstName");
            String lastName = pilot.getString("lastName");

            System.out.println( "Coolness: " + coolness );
            System.out.println( "Altitude: " + altitude );
            System.out.println( "Pilot: " + lastName );
        }
    }

Et ceci est votre exemple-json.txt, devrait être au format json

{
 'foo':'bar',
 'coolness':2.0,
 'altitude':39000,
 'pilot':
     {
         'firstName':'Buzz',
         'lastName':'Aldrin'
     },
 'mission':'apollo 11'
}
23
répondu Kit Ho 2018-09-15 13:38:54

Merci @ Kit Ho pour votre réponse. J'ai utilisé votre code et j'ai constaté que je continuais à courir dans des erreurs où mon InputStream était toujours NULL et classnotfound exceptions lorsque le JSONObject était en cours de création. 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(String[] args) throws Exception {
        File f = new File("file.json");
        if (f.exists()){
            InputStream is = new FileInputStream("file.json");
            String jsonTxt = IOUtils.toString(is, "UTF-8");
            System.out.println(jsonTxt);
            JSONObject json = new JSONObject(jsonTxt);       
            String a = json.getString("1000");
            System.out.println(a);   
        }
    }
}

J'ai trouvé cette réponse éclairante sur la différence entre FileInputStream et getresourceastream. Espérons que cela aide quelqu'un d'autre aussi.

31
répondu janoulle 2017-10-10 17:35:08

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(String filename) throws JSONException, IOException {
        String content = new String(Files.readAllBytes(Paths.get(filename)));
        return new JSONObject(content);
    }

    public static void main(String[] args) throws IOException, JSONException {
        String filename = "path/to/file/abc.json";
        JSONObject jsonObject = parseJSONFile(filename);

        //do anything you want with jsonObject
    }
}
5
répondu IKo 2017-03-29 10:32:36

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

String 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 objet obtenu après l'analyse de la chaîne json avec laquelle travailler.

1
répondu Antariksh 2017-03-29 10:53:14