Skip to content

Commit

Permalink
Add Moshi 1.x.
Browse files Browse the repository at this point in the history
  • Loading branch information
johnjohndoe committed Mar 14, 2016
1 parent a2c538d commit 2aa7a34
Show file tree
Hide file tree
Showing 15 changed files with 213 additions and 1 deletion.
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,4 @@
* Dimitrij Drus
* Arno Puder
* SpaceBison
* Tobias Preuss
1 change: 1 addition & 0 deletions jsonschema2pojo-ant/src/site/Jsonschema2PojoTask.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ <h3>Parameters</h3>
<li><code>JACKSON2</code> (apply annotations from the <a href="https://github.com/FasterXML/jackson-annotations">Jackson 2.x</a> library)</li>
<li><code>JACKSON1</code> (apply annotations from the <a href="http://jackson.codehaus.org/">Jackson 1.x</a> library)</li>
<li><code>GSON</code> (apply annotations from the <a href="https://code.google.com/p/google-gson//">Gson</a> library)</li>
<li><code>MOSHI1</code> (apply annotations from the <a href="https://github.com/square/moshi//">Moshi 1.x</a> library)</li>
<li><code>NONE</code> (apply no annotations at all)</li>
</ul>
</td>
Expand Down
4 changes: 4 additions & 0 deletions jsonschema2pojo-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ public enum AnnotationStyle {
*/
GSON,

/**
* Moshi 1.x
*
* @see <
* href="https://github.com/square/moshi">https://github.com/square/moshi</a>
*/
MOSHI1,

/**
* No-op style, adds no annotations at all.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,8 @@ public interface Annotator {
* annotators, this method will return <code>true</code>. Gson does not
* support 'additional' property values (they are silently discarded at
* deserialization time), hence for Gson annotators, this method would
* return <code>false</code>.
* return <code>false</code>. Moshi 1.x behaves similar to Gson and therefore
* returns <code>false</code>.
*
* @return Whether this annotator has any way to support 'additional
* properties'.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ public Annotator getAnnotator(AnnotationStyle style) {
return new Jackson1Annotator();
case GSON:
return new GsonAnnotator();
case MOSHI1:
return new Moshi1Annotator();
case NONE:
return new NoopAnnotator();
default:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,9 @@ public interface GenerationConfig {
* <li><code>gson</code> (apply annotations from the
* <a href="https://code.google.com/p/google-gson/">gson</a>
* library)</li>
* <li><code>moshi1</code> (apply annotations from the
* <a href="https://github.com/square/moshi">moshi</a>
* library)</li>
* <li><code>none</code> (apply no annotations at all)</li>
* </ul>
* @see AnnotatorFactory
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* Copyright © 2016 Tobias Preuss
*
* 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 org.jsonschema2pojo;

import com.fasterxml.jackson.databind.JsonNode;
import com.squareup.moshi.Json;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JEnumConstant;
import com.sun.codemodel.JFieldVar;

/**
* Annotates generated Java types using Moshi. The annotations used here are most
* useful when the JSON fields have characters (like underscores) that are
* poorly suited for beans. By using the {@link Json} annotation, we
* are able to preserve the original format.
*
* @see <a
* href="https://github.com/square/moshi#custom-field-names-with-json">https://github.com/square/moshi#custom-field-names-with-json</a>
*/
public class Moshi1Annotator extends AbstractAnnotator {

@Override
public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) {
field.annotate(Json.class).param("name", propertyName);
}

@Override
public void enumConstant(JEnumConstant constant, String value) {
constant.annotate(Json.class).param("name", value);
}

@Override
public boolean isAdditionalPropertiesSupported() {
return false;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public void canCreateCorrectAnnotatorFromAnnotationStyle() {
assertThat(factory.getAnnotator(JACKSON), is(instanceOf(Jackson2Annotator.class)));
assertThat(factory.getAnnotator(JACKSON2), is(instanceOf(Jackson2Annotator.class)));
assertThat(factory.getAnnotator(GSON), is(instanceOf(GsonAnnotator.class)));
assertThat(factory.getAnnotator(MOSHI1), is(instanceOf(Moshi1Annotator.class)));
assertThat(factory.getAnnotator(NONE), is(instanceOf(NoopAnnotator.class)));

}
Expand Down
1 change: 1 addition & 0 deletions jsonschema2pojo-gradle-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ jsonSchema2Pojo {
// - jackson2 (apply annotations from the Jackson 2.x library)
// - jackson1 (apply annotations from the Jackson 1.x library)
// - gson (apply annotations from the Gson library)
// - moshi1 (apply annotations from the Moshi 1.x library)
// - none (apply no annotations at all)
annotationStyle = 'jackson'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ dependencies {
compile 'org.glassfish:javax.annotation:10.0-b28'
// Required if generating Gson annotations
compile 'com.google.code.gson:gson:2.5'
// Required if generating Moshi 1.x annotations
compile 'com.squareup.moshi:moshi:1.1.0'
// Required if generating equals, hashCode, or toString methods
compile 'commons-lang:commons-lang:2.6'
// Required if generating JSR-303 annotations
Expand Down Expand Up @@ -98,6 +100,7 @@ jsonSchema2Pojo {
// - jackson2 (apply annotations from the Jackson 2.x library)
// - jackson1 (apply annotations from the Jackson 1.x library)
// - gson (apply annotations from the Gson library)
// - moshi1 (apply annotations from the Moshi 1.x library)
// - none (apply no annotations at all)
annotationStyle = 'gson'

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ dependencies {
compile 'org.glassfish:javax.annotation:10.0-b28'
// Required if generating Gson annotations
compile 'com.google.code.gson:gson:2.5'
// Required if generating Moshi 1.x annotations
compile 'com.squareup.moshi:moshi:1.1.0'
// Required if generating equals, hashCode, or toString methods
compile 'commons-lang:commons-lang:2.6'
// Required if generating JSR-303 annotations
Expand Down Expand Up @@ -96,6 +98,7 @@ jsonSchema2Pojo {
// - jackson2 (apply annotations from the Jackson 2.x library)
// - jackson1 (apply annotations from the Jackson 1.x library)
// - gson (apply annotations from the Gson library)
// - moshi1 (apply annotations from the Moshi 1.x library)
// - none (apply no annotations at all)
annotationStyle = 'gson'

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/**
* Copyright © 2016 Tobias Preuss
*
* 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 org.jsonschema2pojo.integration.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.google.gson.Gson;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import org.apache.commons.io.IOUtils;
import org.jsonschema2pojo.integration.util.Jsonschema2PojoRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import static org.hamcrest.Matchers.*;
import static org.jsonschema2pojo.integration.util.CodeGenerationHelper.config;
import static org.jsonschema2pojo.integration.util.FileSearchMatcher.containsText;
import static org.jsonschema2pojo.integration.util.JsonAssert.assertEqualsJson;
import static org.junit.Assert.assertThat;

public class Moshi1IT {

@Rule
public Jsonschema2PojoRule schemaRule = new Jsonschema2PojoRule();

private Moshi moshi;

@Before
public void setUp() {
moshi = new Moshi.Builder().build();
}

@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void annotationStyleMoshi1ProducesMoshi1Annotations() throws ClassNotFoundException, SecurityException, NoSuchMethodException, NoSuchFieldException {

Class generatedType = schemaRule.generateAndCompile("/json/examples/torrent.json", "com.example",
config("annotationStyle", "moshi1",
"propertyWordDelimiters", "_",
"sourceType", "json"))
.loadClass("com.example.Torrent");

assertThat(schemaRule.getGenerateDir(), not(containsText("org.codehaus.jackson")));
assertThat(schemaRule.getGenerateDir(), not(containsText("com.fasterxml.jackson")));
assertThat(schemaRule.getGenerateDir(), not(containsText("com.google.gson")));
assertThat(schemaRule.getGenerateDir(), not(containsText("@SerializedName")));
assertThat(schemaRule.getGenerateDir(), containsText("com.squareup.moshi"));
assertThat(schemaRule.getGenerateDir(), containsText("@Json"));

Method getter = generatedType.getMethod("getBuild");

assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(nullValue()));
assertThat(generatedType.getAnnotation(JsonInclude.class), is(nullValue()));
assertThat(getter.getAnnotation(JsonProperty.class), is(nullValue()));
}

@Test
public void annotationStyleMoshi1MakesTypesThatWorkWithMoshi1() throws ClassNotFoundException, SecurityException, NoSuchMethodException, NoSuchFieldException, IOException {

ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/json/examples/", "com.example",
config("annotationStyle", "moshi1",
"propertyWordDelimiters", "_",
"sourceType", "json",
"useLongIntegers", true));

assertJsonRoundTrip(resultsClassLoader, "com.example.Torrent", "/json/examples/torrent.json");
assertJsonRoundTrip(resultsClassLoader, "com.example.GetUserData", "/json/examples/GetUserData.json");
}

@SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void enumValuesAreSerializedCorrectly() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/typeWithEnumProperty.json", "com.example",
config("annotationStyle", "moshi1",
"propertyWordDelimiters", "_"));

Class generatedType = resultsClassLoader.loadClass("com.example.TypeWithEnumProperty");
Class enumType = resultsClassLoader.loadClass("com.example.TypeWithEnumProperty$EnumProperty");
Object instance = generatedType.newInstance();

Method setter = generatedType.getMethod("setEnumProperty", enumType);
setter.invoke(instance, enumType.getEnumConstants()[3]);

JsonAdapter jsonAdapter = moshi.adapter(generatedType);
String json = jsonAdapter.toJson(instance);

Map<String, String> jsonAsMap = new Gson().fromJson(json, Map.class);
assertThat(jsonAsMap.get("enum_Property"), is("4 ! 1"));
}

@SuppressWarnings({"unchecked", "rawtypes"})
private void assertJsonRoundTrip(ClassLoader resultsClassLoader, String className, String jsonResource) throws ClassNotFoundException, IOException {
Class generatedType = resultsClassLoader.loadClass(className);

String expectedJson = IOUtils.toString(getClass().getResource(jsonResource));
JsonAdapter<Object> jsonAdapter = moshi.adapter(generatedType);
Object javaInstance = jsonAdapter.fromJson(expectedJson);
String actualJson = jsonAdapter.toJson(javaInstance);

assertEqualsJson(expectedJson, actualJson);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,8 @@ public class Jsonschema2PojoMojo extends AbstractMojo implements GenerationConfi
* <a href="http://jackson.codehaus.org/">Jackson 1.x</a> library)</li>
* <li><code>gson</code> (apply annotations from the
* <a href="https://code.google.com/p/google-gson/">gson</a> library)</li>
* <li><code>moshi1</code> (apply annotations from the
* <a href="https://github.com/square/moshi">moshi 1.x</a> library)</li>
* <li><code>none</code> (apply no annotations at all)</li>
* </ul>
*
Expand Down
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<gradle.version>1.6</gradle.version>
<gson.version>2.5</gson.version>
<moshi.version>1.1.0</moshi.version>
</properties>

<build>
Expand Down Expand Up @@ -296,6 +297,11 @@
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi</artifactId>
<version>${moshi.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.javaparser</groupId>
<artifactId>javaparser</artifactId>
Expand Down

0 comments on commit 2aa7a34

Please sign in to comment.