:JsonPath:リスト部材とJavaオブジェクトにJSONの解析、私はBookクラスに以下のJSONを解析しようとしています
{
"inventory": {
"book": {
"title": "Database Systems",
"authors": [
{"name": "Sudarshan"},
{"name": "Korth"},
{"name": "Silberschatz"}
]
}
}
}
次の定義をフィールドのJSONの注釈があり、持っている
Bookクラス:
package com.example.books
public class Book {
@JsonProperty("title")
private String title;
@JsonProperty("authors")
private List<Author> authors;
public Book() {
authors = new ArrayList<Author>();
}
// constructors, getters, setters
}
public class Author {
@JsonProperty
private String name;
// constructor, getters, setters...
}
私はcom.jayway.jsonpath.JsonPath
を使用してこれを達成しようとしています:
Book book = JsonPath.read(inventoryJson.toString(), "$.inventory.book");
これは、次の例外が発生:私も試してみました
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.example.books.Book
:私はそれを動作させるにはどうすればよい
java.lang.RuntimeException: Can not find Array 'authors' field in class com.example.book.Book
at net.minidev.json.writer.BeansMapper$Bean.startArray(BeansMapper.java:79)
at net.minidev.json.parser.JSONParserBase.readMain(JSONParserBase.java:402)
at net.minidev.json.parser.JSONParserBase.readObject(JSONParserBase.java:542)
at net.minidev.json.parser.JSONParserBase.readFirst(JSONParserBase.java:297)
at net.minidev.json.parser.JSONParserBase.parse(JSONParserBase.java:154)
at net.minidev.json.parser.JSONParserString.parse(JSONParserString.java:58)
at net.minidev.json.parser.JSONParser.parse(JSONParser.java:263)
at net.minidev.json.JSONValue.parse(JSONValue.java:206)
at com.jayway.jsonpath.spi.mapper.JsonSmartMappingProvider.map(JsonSmartMappingProvider.java:82)
at com.jayway.jsonpath.internal.JsonContext.convert(JsonContext.java:192)
at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:158)
:
Book book = JsonPath.parse(inventoryJson.toString()).read("$.inventory.book", Book.class);
この1つは、今異なる例外を与えますか?
オリジナルクラス:
http://pastebin.com/SAhipfxL
http://pastebin.com/vWfWsaqN
http://pastebin.com/7tqhJfw3
完全なスタックトレース:私はあなたの質問からコードにミスのシリーズを見つけ http://pastebin.com/QWV89Hgj
ご迷惑をおかけして申し訳ありません。私はちょうど私が持っている元のクラスを模倣するためにこれらのダミーのクラスを作成し、受け取った例外を指摘します。私は訂正して質問を編集しましたが、それはまだ動作しません。 – user87407
1)あなたは 'JSON'を修正しませんでした。 2)それは明確ではない、クラスをトップクラスとして宣言したかどうか? 3)**は動作するはずです - 私は私の修正でテストしました。 – Andremoniy
完全な例外スタックトレースとともに、コードのペーストビンリンクを追加しました。それにはまだ "本"があります(それを忘れてしまった)。 – user87407