[英]How to parse JSON file?
簡單的情況 -
我試過gson,來自json.org的軟件包,但似乎無法與之相提並論。
有人可以在Java中提供一個關於如何獲取文件的清晰樣本,閱讀它,最后使用json objec我可以從中獲取鍵/值對。
考慮一下:
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());
}
}
}
從邏輯上講,它似乎沒問題,但是,我得到一個例外:
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)
你能告訴我我錯過了嗎?
使用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();
....
}
你當然應該避免從字符串重新解析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!
}
}
我們使用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;
}
以下是如何調用它的代碼:
JsonEmployee jsonEmployee = getJsonObject(inputStream, JsonEmployee.class);
JsonEmployee.java只是POJO
XStream適用於JSON: http : //x-stream.github.io/json-tutorial.html
由於XStream的靈活架構,JSON映射的處理就像處理XML文檔一樣簡單。 您所要做的就是使用適當的驅動程序初始化XStream對象,並准備將對象序列化為(和)JSON。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.