Posted In: Jackson 1X, JSON

Generate Json Schema from POJO – Jackson 1X

 

1. Example is using Address POJO with multiple fields.


package com.example1;

public class Address {
	private String addressID;
	private String country;
	private String state;
	private String pinCode;

	public String getAddressID() {
		return addressID;
	}

	public void setAddressID(String addressID) {
		this.addressID = addressID;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getPinCode() {
		return pinCode;
	}

	public void setPinCode(String pinCode) {
		this.pinCode = pinCode;
	}
}

 

2. Use org.codehaus.jackson.schema.JsonSchema class to get schema from POJO class

 

package com.example;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.schema.JsonSchema;

//Generate Json Schema from POJO
public class Main5 {
	public static void main(String a[]) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			mapper.configure(
			        SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING,
			        true);
			JsonSchema schema = mapper
			        .generateJsonSchema(Address.class);
			System.out.println(
			        mapper.writerWithDefaultPrettyPrinter()
			                .writeValueAsString(schema));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

3. Schema generated

{
  "type" : "object",
  "properties" : {
    "addressID" : {
      "type" : "string"
    },
    "country" : {
      "type" : "string"
    },
    "state" : {
      "type" : "string"
    },
    "pinCode" : {
      "type" : "string"
    }
  }
}

 
 

Tags: ,

by , on February 21st, 2017

  • Categories