从json文本文件加载JSONObject的最佳方法是什么? [英] What’s the best way to load a JSONObject from a json text file?
本文介绍了从json文本文件加载JSONObject的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将包含JSON的文件加载到JSONObject中的最简单方法是什么。
What would be the easiest way to load a file containing JSON into a JSONObject.
目前我使用的是json-lib。
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));
输出为:
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格式
and this is your sample-json.txt , should be in json format
{
'foo':'bar',
'coolness':2.0,
'altitude':39000,
'pilot':
{
'firstName':'Buzz',
'lastName':'Aldrin'
},
'mission':'apollo 11'
}
这篇关于从json文本文件加载JSONObject的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文