Java 如何解析JSON文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3000778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse JSON file?
提问by James Raitsev
Simple situation -
简单的情况——
- read a json file
- discover all key-value pairs
- compare key-value pairs
- 读取一个json文件
- 发现所有键值对
- 比较键值对
I tried gson, package from json.org, but can't seem to get far with it.
我尝试了 json.org 中的 gson 包,但似乎无法实现。
Can someone please provide a clear sample in Java on how to take a file, read it, end up with json objec I can get key/value pairs from.
有人可以在Java中提供一个关于如何获取文件、读取文件、最终得到json对象的清晰示例,我可以从中获取键/值对。
Consider this:
考虑一下:
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());
}
}
}
Logically, it seems alright, however, i get an exception:
从逻辑上讲,这似乎没问题,但是,我得到了一个例外:
Exception in thread "main" java.lang.IllegalStateException
at com.google.gson.JsonArray.getAsString(JsonArray.java:133)
at com.cme.esg.bk.TryGson.runThroughJson(TryGson.java:46)
at com.cme.esg.bk.TryGson.runThroughJson(TryGson.java:44)
at com.cme.esg.bk.TryGson.goForIt(TryGson.java:32)
at com.cme.esg.bk.TryGson.main(TryGson.java:16)
Can you please advise that am i missing.
你能告诉我我失踪了吗?
采纳答案by Chris Lercher
With Gson (assuming that you have on object {...}
on the top level of your json file):
使用 Gson(假设您在{...}
json 文件的顶层有对象):
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();
....
}
In response to your comment:
回应你的评论:
You should certainly avoid re-parsing the json from a string. Use something like:
您当然应该避免从字符串中重新解析 json。使用类似的东西:
... 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!
}
}
回答by Brian
XStream is good for JSON: http://x-stream.github.io/json-tutorial.html
XStream 适用于 JSON:http: //x-stream.github.io/json-tutorial.html
Due to XStream's flexible architecture, handling of JSON mappings is as easy as handling of XML documents. All you have to do is to initialize XStream object with an appropriate driver and you are ready to serialize your objects to (and from) JSON.
由于 XStream 的灵活架构,处理 JSON 映射就像处理 XML 文档一样简单。您所要做的就是使用适当的驱动程序初始化 XStream 对象,然后您就可以将对象序列化为(和来自)JSON。
回答by Rachel
We use Jaskson parser, here are the sample code:
我们使用 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;
}
Here is the code how to invoke it:
这是如何调用它的代码:
JsonEmployee jsonEmployee = getJsonObject(inputStream, JsonEmployee.class);
JsonEmployee.java is just POJO
JsonEmployee.java 只是 POJO