3

I am writing something that will need to work with the JSON metadata for an object.

For example given the sample class below:

public class MyClassA
{
    @JsonProperty("a")
    private String a;

    @JsonProperty("anothername")
    private Integer b;

    @JsonProperty("c")
    private MyClassB c;
}

public class MyClassB
{
    private Integer z = -1;

    @JsonValue
    public Integer toInteger()
    {
        return z;             
    }
}

I would like to know MyClassA maps to the following property names and JSON primitive types: (a - String, anothername - Number, c - Number) without doing the same introspection Jackson may be doing under the hood.

It's not immediately apparent what APIs under Jackson are available for doing that.

Kevin Deenanauth
  • 876
  • 8
  • 22

1 Answers1

1

What you are looking for is the schema describing your JSON. There is a jackson module for just this. It can be used like below:

Objects:

class Entity {

    private Long id;
    private List<Profile> profiles;

    // getters/setters
}

class Profile {

    private String name;
    private String value;
    // getters / setters
}

Code to generate schema:

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper;

public class JacksonProgram {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
        mapper.acceptJsonFormatVisitor(Entity.class, visitor);
        JsonSchema schema = visitor.finalSchema();
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema));
    }
}

Output:

{
  "type" : "object",
  "properties" : {
    "id" : {
      "type" : "integer"
    },
    "profiles" : {
      "type" : "array",
      "items" : {
        "type" : "object",
        "properties" : {
          "name" : {
            "type" : "string"
          },
          "value" : {
            "type" : "string"
          }
        }
      }
    }
  }
}

Source: Create JSON schema from Java class

Community
  • 1
  • 1
Danny
  • 7,368
  • 8
  • 46
  • 70
  • 1
    At least, you could add the page from which you copy above example... Source: http://stackoverflow.com/questions/17783909/create-json-schema-from-java-class/17786708#17786708 – Michał Ziober Mar 18 '14 at 19:58