0

我在这里关注这个教程,我的 JSON 对象几乎相同,除了我有这种格式:

{"user":{
    "SomeKeys":"SomeValues",
    "SomeList":["val1","val2"]
    }
}

这是我的相关代码:

Object obj = parser.parse(new FileReader("exampleJson.json"));

JSONObject jsonObject = (JSONObject) obj;
JSONObject user = (JSONObject) jsonObject.get("user");
JSONArray list = (JSONArray) user.get("SomeList");

然后我的程序关闭并从键等中获取值。或者它会但我NullPointerException从 eclipse 中得到一个。为什么是这样?

它应该将我的.json文件jsonObject解包为 ,将“user”键解包为 JSONObject user,然后将“SomeList”键解包为名为list. 除非它这样做,否则它必须尝试将其中一个val1val2放入 JSONArray 的一部分中,该部分不存在,只是指向null. 我做了什么让这个错?

如何修复我的程序?

4

2 回答 2

1

您的代码对我来说效果很好

public class App {

    public static void main(final String[] args) throws FileNotFoundException, IOException, ParseException {
        final Object obj = new JSONParser().parse(new FileReader("D:/a.json"));
        final JSONObject jsonObject = (JSONObject) obj;
        final JSONObject user = (JSONObject) jsonObject.get("user");
        final JSONArray list = (JSONArray) user.get("SomeList");
        System.out.println(list);
    }
} 

文件D:/exampleJson.json

{"user":{
    "SomeKeys":"SomeValues",
    "SomeList":["val1","val2"]
    }
}  

输出是

["val1","val2"]
于 2012-09-19T18:50:05.450 回答
1

使用完全相同的 json 文件:

{"user":{
    "SomeKeys":"SomeValues",
    "SomeList":["val1","val2"]
    }
}

这是我使用的代码(通过导入来确保我们拥有相同的代码):

import java.io.FileReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class Test {

    public static void main(String[] args) throws Exception {
        Object obj = new JSONParser().parse(new FileReader("t.json"));

        JSONObject jsonObject = (JSONObject) obj;
        JSONObject user = (JSONObject) jsonObject.get("user");
        JSONArray list = (JSONArray) user.get("SomeList");
        System.out.println(list);
    }
}

这是输出:

["val1","val2"]

我使用 maven 和 m2e 来导入库。用于此测试的版本是json-simple-1.1.jar.

于 2012-09-19T18:56:35.850 回答