Java 如何解析JSON文件?
简单情况-Java 如何解析JSON文件?,java,json,Java,Json,简单情况- 读取json文件 发现所有键值对 比较键值对 我尝试了来自json.org的gson软件包,但似乎没有成功 有没有人能用Java提供一个清晰的示例,说明如何获取文件,读取文件,最终得到json objec,我可以从中获取键/值对 考虑这一点: private void runThroughJson(JsonObject jsonObject) { for (final Entry<String, JsonElement> entry : jsonObject.en
private void runThroughJson(JsonObject jsonObject) {
for (final Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final String key = entry.getKey();
final JsonElement value = entry.getValue();
System.out.println(key + " - " + value);
if (value.isJsonObject()) {
runThroughJson(value.getAsJsonObject());
} else {
int ix = value.getAsString().indexOf('[');
int ig = value.getAsString().lastIndexOf(']');
System.out.println(ix);
System.out.println(ig);
String a = value.getAsString().substring(ix, ig);
JsonElement jsonElement = parser.parse(a);
runThroughJson(jsonElement.getAsJsonObject());
}
}
}
请您告知我是否丢失了。使用Gson(假设您的json文件的顶层有on object{…}
):
XStream适用于JSON:
由于XStream灵活的体系结构,处理JSON映射与处理XML文档一样简单。您只需使用适当的驱动程序初始化XStream对象,就可以将对象序列化到(或从)JSON。我们使用Jaskson解析器,下面是示例代码:
protected T getJsonObject(InputStream inputStream, Class<T> className) throws JsonParseException,
JsonMappingException, IOException {
// Deserialize input to Json object
ObjectMapper mapper = new ObjectMapper();
T jsonSource = mapper.readValue(inputStream, className);
return jsonSource;
}
java只是POJOChris——你太棒了。非常感谢你的帮助!我将使用递归深入到内部元素。gson是否提供了删除[]的方法?我不确定我是否理解“删除[]”在本文中的含义,但您可以始终使用
value.isJsonArray()
检查当前元素是否为数组,然后决定放弃它。JsonObject以{}开头和结尾。当我往下钻时,我看到了[{}]。在这种情况下,如果(value.isJsonObject()){loop(value.getAsJsonObject());}或者{int ix=value.getAsString().indexOf('[');int-ig=value.getAsString().lastIndexOf(']);字符串a=value.getAsString().substring(ix,ig);JsonElement-JsonElement=parser.parse(a);loop(JsonElement.getasonobject()); }
final JsonParser parser = new JsonParser();
final JsonElement jsonElement = parser.parse(new FileReader("/path/to/myfile"));
final JsonObject jsonObject = jsonElement.getAsJsonObject();
for (final Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final String key = entry.getKey();
final JsonElement value = entry.getValue();
....
}
... else if (value.isJsonArray()) {
final JsonArray jsonArray = value.getAsJsonArray();
if (jsonArray.size() == 1) {
runThroughJson(jsonArray.get(0));
} else {
// perform some error handling, since
// you expect it to have just one child!
}
}
protected T getJsonObject(InputStream inputStream, Class<T> className) throws JsonParseException,
JsonMappingException, IOException {
// Deserialize input to Json object
ObjectMapper mapper = new ObjectMapper();
T jsonSource = mapper.readValue(inputStream, className);
return jsonSource;
}
JsonEmployee jsonEmployee = getJsonObject(inputStream, JsonEmployee.class);