2015-12-05 16 views
10

Ich bekomme ein großes JSON-Dokument und ich möchte nur einen Teil davon zu meinen Java-Klassen analysieren. Ich dachte daran, etwas wie jsonpath zu verwenden, um partielle Daten daraus zu extrahieren, anstatt eine komplette Hierarchie von Java-Klassen zu erstellen.Jsonpath mit Jackson oder Gson

Unterstützt Jackson oder Gson jsonpath in irgendeiner Weise? Wenn ja, können Sie mir bitte einige Beispiele nennen oder auf eine andere Standardbibliothek zu diesem Zweck verweisen?

Zum Beispiel kann sagen, ich habe ein Dokument unten, und ich möchte nur unter Daten aus es in meinen Java-Klassen extrahieren:

$ .store.book [0] - Nur erstes Buch $ .store.bicycle .Preis - Preis der Fahrrad

{ 
    "store": { 
     "book": [ 
      { 
       "category": "reference", 
       "author": "Nigel Rees", 
       "title": "Sayings of the Century", 
       "price": 8.95 
      }, 
      { 
       "category": "fiction", 
       "author": "Evelyn Waugh", 
       "title": "Sword of Honour", 
       "price": 12.99 
      }, 
      { 
       "category": "fiction", 
       "author": "Herman Melville", 
       "title": "Moby Dick", 
       "isbn": "0-553-21311-3", 
       "price": 8.99 
      }, 
      { 
       "category": "fiction", 
       "author": "J. R. R. Tolkien", 
       "title": "The Lord of the Rings", 
       "isbn": "0-395-19395-8", 
       "price": 22.99 
      } 
     ], 
     "bicycle": { 
      "color": "red", 
      "price": 19.95 
     } 
    }, 
    "expensive": 10 
} 
+0

Keine dieser zwei Bibliotheken hat native jsonpath Unterstützung; Es gibt eine Bibliothek, die allerdings an Jackson arbeitet. – fge

Antwort

11

Die Jayway JsonPath Bibliothek hat die Unterstützung für Werte mit einem JSON Pfad zu lesen.

Zum Beispiel:

String json = "..."; 

Map<String, Object> book = JsonPath.read(json, "$.store.book[0]"); 
System.out.println(book); // prints {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95} 

Double price = JsonPath.read(json, "$.store.bicycle.price"); 
System.out.println(price); // prints 19.95 

Sie können auch Karte JSON-Objekte direkt auf Klassen, wie in Gson oder Jackson:

Book book = JsonPath.parse(json).read("$.store.book[0]", Book.class); 
System.out.println(book); // prints Book{category='reference', author='Nigel Rees', title='Sayings of the Century', price=8.95} 

Wenn Sie speziell Gson oder Jackson verwenden mögen das zu tun Deserialisierung (die Standardeinstellung ist die Verwendung von JSON-Smart). Sie können auch Folgendes konfigurieren:

Weitere Informationen finden Sie unter the documentation.

Verwandte Themen