将包含JSON的文件加载到JSONObject的最简单方法是什么。
目前,我正在使用json-lib。
这是我所拥有的,但是会引发异常:
XMLSerializer xml = new XMLSerializer(); JSON json = xml.readFromFile("samples/sample7.json”); //line 507 System.out.println(json.toString(2));
输出为:
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)
试试这个:
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 ); } }
这是您的sample-json.txt,应为json格式
{ 'foo':'bar', 'coolness':2.0, 'altitude':39000, 'pilot': { 'firstName':'Buzz', 'lastName':'Aldrin' }, 'mission':'apollo 11' }