Search code examples
jsonrestjacksongsonminimal-json

JSON parsing without using Java objects


I want to parse JSON data from a RESTful service.

Unlike a SOAP-based service, where a service consumer can create stubs and skeleton from WSDL, in the case of the RESTful service, the service consumer gets a raw JSON string.

Since the service consumer does not have a Java object matching the JSON structure, we are not able to use the JSON to Java Mappers like GSON, Jackson etc.

One another way is to use parsers like JsonPath, minimal-json, etc which help traversing the JSON structure and read the data.

Is there any better way of reading JSON data?


Solution

  • The official docs for Jackson mention 3 different ways to parse a JSON doc from Java. The first 2 do not require "Java object matching the JSON structure". In Summary :

    • Streaming API (aka "Incremental parsing/generation") reads and writes JSON content as discrete events.
    • Tree Model provides a mutable in-memory tree representation of a JSON document. ObjectMapper can build trees that consist of JsonNode nodes.
    • Data Binding converts JSON to and from POJOs based either on property accessor conventions or annotations.
      1. With simple data binding you convert to and from Java Maps, Lists, Strings, Numbers, Booleans and nulls
      2. With full data binding you convert to and from any Java bean type (as well as "simple" types mentioned above)

    Another option is to generate Java Beans from JSON documents. You mileage may vary and you may/probably will have to modify the generated files. There are at least 5 online tools for that purpose that you can try:

    There are also IDE plugins that you can use. For instance this one for Intellij https://plugins.jetbrains.com/idea/plugin/7678-jackson-generator-plugin