Create JSON schema from Java class

Gson library probably does not contain any feature like that but you can try to solve your problem with Jackson library and jackson-module-jsonSchema module. For example, for below classes:

class Entity {

    private Long id;
    private List<Profile> profiles;

    // getters/setters
}

class Profile {

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

this program:

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));
    }
}

Prints below schema:

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

Have a look at JSONschema4-mapper project. With following setup:

SchemaMapper schemaMapper = new SchemaMapper();
JSONObject jsonObject = schemaMapper.toJsonSchema4(Entity.class, true);
System.out.println(jsonObject.toString(4));

you get following JSON schema for classes mentioned in Michal Ziober's answer to this question:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "additionalProperties": false,
    "type": "object",
    "definitions": {
        "Profile": {
            "additionalProperties": false,
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "value": {"type": "string"}
            }
        },
        "long": {
            "maximum": 9223372036854775807,
            "type": "integer",
            "minimum": -9223372036854775808
        }
    },
    "properties": {
        "profiles": {
            "type": "array",
            "items": {"$ref": "#/definitions/Profile"}
        },
        "id": {"$ref": "#/definitions/long"}
    }
}

Tags:

Java

Json

Gson