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)
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With