Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What’s the best way to load a JSONObject from a json text file?

Tags:

java

json

What would be the easiest way to load a file containing JSON into a JSONObject.

At the moment I am using json-lib.

This is what I have, but it throws an exception:

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

The output is:

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) 
like image 350
Larry Avatar asked Sep 18 '11 18:09

Larry


People also ask

How do I get JSONObject?

getJsonObject() Method It is used to get the (JsonObject)get(name). The method parses an argument name of type String whose related value is to be returned. It returns the object of the associated mapping for the parse's parameter. It returns null if the object has no mapping for the parameter.

How do you load a JSON object in Python?

The load()/loads() method is used for it. If you have used JSON data from another program or obtained as a string format of JSON, then it can easily be deserialized with load()/loads(), which is usually used to load from string, otherwise, the root object is in list or dict. See the following table given below. json.


1 Answers

Thanks @Kit Ho for your answer. I used your code and found that I kept running into errors where my InputStream was always null and ClassNotFound exceptions when the JSONObject was being created. Here's my version of your code which does the trick for me:

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

I found this answer to be enlightening about the difference between FileInputStream and getResourceAsStream. Hope this helps someone else too.

like image 146
janoulle Avatar answered Sep 20 '22 09:09

janoulle