我的第一个问题。 我对android和json有点新鲜。
我有一个带有一些值的.json文件(见下文)。我需要解析它,我试过但我得到了一个nullpointer异常。任何帮助都会很棒!
{
"i": 475,
"lp": "NEW",
"c": "tlf",
"dmc": 0,
"hfg": false,
"b": [
"No",
"Yes"
],
"t": [
{
"i": 131321,
"d": [
{
"d": "2014-07-01T08:32:08",
"lm": 1,
"s": 0,
"b": 33,
"i": 1,
"sS": 63,
"bV": 14.1,
"h": 0.9,
"mi": 137385101,
"x": 0,
"de": 0
},
{
"d": "2014-07-01T08:39:08",
"lm": 1,
"s": 0,
"b": 34,
"i": 1,
"sS": 63,
"bV": 14.1,
"h": 0.9,
"mi": 137385102,
"x": 0,
"de": 0
}
],
"m": [
{
"a": 44.409315,
"o": 26.204476,
"b": 239,
"f": 1,
"i": 137385102
},
{
"a": 44.409175,
"o": 26.203828,
"b": 255,
"f": 2,
"i": 137385103
}
],
"p": {
"a": 0,
"o": 0
}
}
],
"e": [
]
}
代码:
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"Chart-data-source.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
错误: 引起:java.lang.NullPointerException 在com.chartdata.Main.onCreate(Main.java:47) - (br.close();这是第47行)
答案 0 :(得分:0)
要从文件中读取json,请尝试使用此方法
public static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}
调用方法如:
String myJsonString = readFile("C:/pathToJsonFile/folderjsonFlex.json", StandardCharsets.UTF_8);
然后创建json,只需使用
JSONObject myCoolJson = new JSONObject(myJsonString);