Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions jsonschema-generator-parent/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@
<version.swagger-2>2.2.5</version.swagger-2>
<!-- maven plugin runtime dependencies -->
<version.classgraph>4.8.149</version.classgraph>
<version.gson>2.11.0</version.gson>
</properties>

<dependencyManagement>
Expand Down Expand Up @@ -211,6 +212,11 @@
<artifactId>classgraph</artifactId>
<version>${version.classgraph}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${version.gson}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
Expand Down
64 changes: 64 additions & 0 deletions jsonschema-module-gson/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Java JSON Schema Generation – Module Gson
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.victools/jsonschema-module-jackson/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.victools/jsonschema-module-jackson)

Module for the [jsonschema-generator](../jsonschema-generator) – deriving JSON Schema attributes from `gson` annotations.

## Features
1. Override a field's/method's property name as per `@SerializedName` annotations.
2. Ignore fields/methods that are marked with a `@Expose` annotation.

----

## Documentation
JavaDoc is being used throughout the codebase, offering contextual information in your respective IDE or being available online through services like [javadoc.io](https://www.javadoc.io/doc/com.github.victools/jsonschema-module-jackson).

Additional documentation can be found in the [Project Wiki](https://github.com/victools/jsonschema-generator/wiki).

----

## Usage
### Dependency (Maven)
```xml
<dependency>
<groupId>com.github.victools</groupId>
<artifactId>jsonschema-module-gson</artifactId>
<version>[4.21.0,5.0.0)</version>
</dependency>
```

Since version `4.7`, the release versions of the main generator library and this module are aligned.
It is recommended to use identical versions for both dependencies to ensure compatibility.

### Code
#### Passing into SchemaGeneratorConfigBuilder.with(Module)
```java
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
import com.github.victools.jsonschema.module.gson.GsonModule;
```
```java
GsonModule module = new GsonModule();
SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09)
.with(module);
```

#### Complete Example
```java
import com.fasterxml.jackson.databind.JsonNode;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
import com.github.victools.jsonschema.module.gson.GsonModule;
```
```java
GsonModule module = new GsonModule();
SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON)
.with(module);
SchemaGeneratorConfig config = configBuilder.build();
SchemaGenerator generator = new SchemaGenerator(config);
JsonNode jsonSchema = generator.generateSchema(YourClass.class);

System.out.println(jsonSchema.toString());
```
55 changes: 55 additions & 0 deletions jsonschema-module-gson/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.github.victools</groupId>
<artifactId>jsonschema-generator-parent</artifactId>
<version>4.35.0</version>
<relativePath>../jsonschema-generator-parent/pom.xml</relativePath>
</parent>
<artifactId>jsonschema-module-gson</artifactId>

<name>Java JSON Schema Generator Module – GSON</name>
<description>Module for the jsonschema-generator – deriving JSON Schema attributes from GSON annotations</description>
<url>https://github.com/victools/jsonschema-generator</url>

<properties>
<java.module.name>com.github.victools.jsonschema.module.gson</java.module.name>
</properties>

<dependencies>
<dependency>
<groupId>com.github.victools</groupId>
<artifactId>jsonschema-generator</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.moditect</groupId>
<artifactId>moditect-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright 2019 VicTools.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.github.victools.jsonschema.module.gson;
import com.github.victools.jsonschema.generator.Module;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.Optional;

/**
* Module for setting up schema generation aspects based on {@code gson-annotations}.
* <ul>
* <li>Apply alternative property names defined in {@link SerializedName} annotations.</li>
* <li>Exclude properties that are deemed to be ignored per the use of {@link Expose}.</li>
* </ul>
*/
public class GsonModule implements Module {

/**
* Constructor, without any additional options.
*
* @see GsonModule
*/
public GsonModule() {
}

@Override
public void applyToConfigBuilder(SchemaGeneratorConfigBuilder builder) {
//if the field should be included yes/no based on GSON Expose declaration
builder.forFields().withIgnoreCheck(field -> {
Expose annotation = field.getAnnotationConsideringFieldAndGetter(Expose.class);
return annotation != null && !annotation.serialize();
});

//Take the property name from the GSON SerializedName declaration
builder.forFields().withPropertyNameOverrideResolver(
field -> Optional.ofNullable(field.getAnnotationConsideringFieldAndGetter(SerializedName.class))
.map(SerializedName::value).orElse(null));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright 2020 VicTools.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.github.victools.jsonschema.module.gson;

import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.victools.jsonschema.generator.Option;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

import com.google.gson.annotations.SerializedName;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;

/**
* Integration test of this module being used in a real SchemaGenerator instance.
*/
public class IntegrationTest {

@Test
public void testIntegration() throws Exception {
GsonModule module = new GsonModule();
SchemaGeneratorConfig config = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_7, OptionPreset.PLAIN_JSON)
.with(Option.DEFINITIONS_FOR_MEMBER_SUPERTYPES, Option.NULLABLE_ARRAY_ITEMS_ALLOWED)
.with(Option.NONSTATIC_NONVOID_NONGETTER_METHODS, Option.FIELDS_DERIVED_FROM_ARGUMENTFREE_METHODS)
.with(module)
.build();
SchemaGenerator generator = new SchemaGenerator(config);
JsonNode result = generator.generateSchema(TestClass.class);

String rawJsonSchema = result.toString();
System.out.println(rawJsonSchema);
JSONAssert.assertEquals('\n' + rawJsonSchema + '\n',
loadResource("integration-test-result.json"), rawJsonSchema, JSONCompareMode.STRICT);
}

private static String loadResource(String resourcePath) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
try (InputStream inputStream = IntegrationTest.class
.getResourceAsStream(resourcePath);
Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
while (scanner.hasNext()) {
stringBuilder.append(scanner.nextLine()).append('\n');
}
}
return stringBuilder.toString();
}

static class TestClass {

@SerializedName(value = "field_with_overridden_name")
public boolean originalFieldName;

public TestEnum enumValueHandledByStandardOption;

}

enum TestEnum {
A, B, C
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"enumValueHandledByStandardOption": {
"type": "string",
"enum": [
"A",
"B",
"C"
]
},
"field_with_overridden_name": {
"type": "boolean"
}
}
}
12 changes: 12 additions & 0 deletions jsonschema-module-gson/src/test/resources/logback.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>

<root level="warn">
<appender-ref ref="console"/>
</root>
</configuration>
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<module>jsonschema-generator-bom</module>
<module>jsonschema-generator-parent</module>
<module>jsonschema-generator</module>
<module>jsonschema-module-gson</module>
<module>jsonschema-module-jackson</module>
<module>jsonschema-module-jakarta-validation</module>
<module>jsonschema-module-javax-validation</module>
Expand Down