EzDevInfo.com

jsonschema2pojo

Generates Java types from JSON Schema (or example JSON) and annotates those types for data-binding with Jackson 1.x or 2.x, Gson, etc jsonschema2pojo generate plain old java objects from json or json-schema.

How to set the annotationStyle to Gson using jsonschema2pojo-core?

I´m using the jsonschema2pojo-core to parse from JSON to POJO. The thing is I´d like to set the annotationStyle to GSON. (default is Jackson).

Any idea?

Thanks a lot.


Source: (StackOverflow)

jsonschema2pojo: referencing objects of the same type

I need to generate Java classes from a JSON schema file and came across jsonschema2pojo. However, I encountered a "problem" when using the ref keyword.

For example, if I use the following schema from http://spacetelescope.github.io/understanding-json-schema/structuring.html#extending:

{
  "$schema": "http://json-schema.org/draft-04/schema#",

  "definitions": {
    "address": {
      "type": "object",
      "properties": {
        "street_address": { "type": "string" },
        "city":           { "type": "string" },
        "state":          { "type": "string" }
      },
      "required": ["street_address", "city", "state"]
    }
  },

  "type": "object",

  "properties": {
    "billing_address": { "$ref": "#/definitions/address" },
    "shipping_address": { "$ref": "#/definitions/address" }
  }
}

As expected, it generated a class named whatever you want to call it, containing an attribute billingAddress and an attribute shippingAddress.

However, it also generated two separate classes BillingAddress and ShippingAddress even though both attributes are referencing to address. Hence, I would rather have both attributes of type Address.

Is this possible to achieve with jsonschema2pojo?


Source: (StackOverflow)

Advertisements

Why does Jackson ignore @JsonCreator annotation in my auto-generated POJO Enum?

As usual, there is probaly a very simple solution to my problem:

I have a JSON schema snippet that defines the following enum:

"title" : {
    "type": "string",
    "enum": ["Mr", "Miss", "Mrs", "Ms"],
    "description": "The person's title"
 }

My company's framework then uses jsonschema2pojo and maven to create the necessary POJO (Title lives in Clazz, as title is part of clazz in the JSON schema - with clazz as a name being made up - replace it with employee or customer or whatever you like):

Generated POJO

@Generated("org.jsonschema2pojo")
public static enum Title {

    MR("Mr"),
    MISS("Miss"),
    MRS("Mrs"),
    MS("Ms");
    private final String value;
    private static Map<String, Clazz.Title> constants = new HashMap<String, Clazz.Title>();

    static {
        for (Clazz.Title c: values()) {
            constants.put(c.value, c);
        }
    }

    private Title(String value) {
        this.value = value;
    }

    @JsonValue
    @Override
    public String toString() {
        return this.value;
    }

    @JsonCreator
    public static Clazz.Title fromValue(String value) {
        Clazz.Title constant = constants.get(value);
        if (constant == null) {
            throw new IllegalArgumentException(value);
        } else {
            return constant;
        }
    }
}

When I run a request containing the following against it:

...
  "title" : "Mr",
...

I get this error thrown back at me:

com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of com.example.foo.representations.jaxb.Clazz$Title from String value 'Mr': value not one of declared Enum instance names: [Mr, Miss, Mrs, Ms]  at [Source: org.apache.cxf.transport.http.AbstractHTTPDestination$1@1a372b7; line: 4, column: 3] (through reference chain: com.example.foo.representations.jaxb.MySchema["Clazz"]->com.example.foo.representations.jaxb.Clazz["title"])

Clearly, "Mr" is in the Enum.

When debugging, I can see that it runs through the following classes (stack):

findEnum():120, EnumResolver (com.fasterxml.jackson.databind.util)
deserialize():79, EnumDeserializer (com.fasterxml.jackson.databind.deser.std)

It looks like they are only interested in the Enum's "keys" (i.e. constants, e.g. "MR" instead of "Mr"). I'm guessing that the @JsonCreator annotation is ignored for some reason.

Any idea how I can fix that issue? Is there a configuration value that might be set anywhere that might cause this behaviour? (I'm working on a big projects; if I know what I need to look for I can search the code base; maybe another developer "misconfigured" something somewhere...) Or might the issue be that Title lives in Clazz? Do I need to throw an @JsonProperty in for good measure? (If so, how exactly?)

We are using jackson-core, -annotations, and -databind 2.4.2.

Update: I tried this as a stand-alone project, with the following code, and it worked flawlessly - which means there must be some sort of setting that prevents the annotation from being taken into account...

ObjectMapper mapper = new ObjectMapper(); // create once, reuse
Clazz value = mapper.readValue(new File("resources/data.json"), Clazz.class);

Source: (StackOverflow)

How to enforce restrictions in Json Schema

we are using JsonSchema to document our Rest APIs and I need to be sure that every string, number, array has restrictions on their maximum size applied to them i.e.

  • all strings have a maxLength & pattern set
  • all integers/numbers have a maximum set
  • all arrays have a maxItems set

This will then allow us to run javax validation on the POJOs generated from the JsonSchema (we use jsonschema2pojo with JSR303 annotations).

I'd rather not manually eyeball every schema passed my way so wondering if there was any automated tool to check every element for these items? If not I may be writing one :-)

Many thanks


Source: (StackOverflow)

How to import a class from a jar in a pojo generation from json

I am using jsonschema2pojo to generate a pojo from a schema like the following:

{
    "$schema":"http://json-schema.org/draft-04/hyper-schema#",
    "type":"object",
    "name":"person",
    "description":"Details about the card to be tokenized.",
    "properties":{
        "name":{"type":"string"},
        "address":{
            "type":"object",
            "$ref":"common_components/address.json"
         },
    }
}

When I run jsonschema2pojo it generates two classes Person.java and Address.java under the same package.

The Pojo for Address also exists in the package generated for the common components.

My question is: is it possible that jsonschema2pojo generates Person.java using an import of the Pojo generated for Address under the common components package instead of generating a new Pojo?


Source: (StackOverflow)

Deserialization of Polymorphic types with Jersey default implementation: MOXy

All my entities inherit from a class named EntidadeBase:

@MappedSuperclass
public abstract class EntidadeBase implements Serializable {

private static final long serialVersionUID = -3912856473903279467L;

@Id
@QueryParam("id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@PodamStrategyValue(value = NullStrategy.class)
private Long id;

@Column(name = "cadastro_data", nullable = false)
@PodamStrategyValue(value = PastDateStrategy.class)
private LocalDate dataCadastro;

@Column(name = "modificado_data", nullable = false)
@PodamStrategyValue(value = PastDateStrategy.class)
private LocalDate dataModificacao;

@QueryParam("modificado")
@Column(nullable = false)
@PodamBooleanValue(boolValue = false)
private Boolean modificado;

@QueryParam("ativo")
@Column(nullable = false)
@PodamBooleanValue(boolValue = true)
private Boolean ativo;
}

Its a JAX-RS/Jersey Webservice deployed on tomcat 8 that actually use default Jersey impl for POJO binding: MOXy.

My problem is that, for example, when I send a PUT request with a JSON entity inside it, the EntidadeBase fields are not parsed to my EndPoint object

Heres an example:

@PUT
@Override
@Transactional(qualifier = ForTransaction.class)
public Response atualizar(@NotNull Abrangencia entidade) {
    return super.atualizar(entidade);
}

How can I manage to make MOXy parse JSON values to the fields of the inherited superclasses?


Source: (StackOverflow)

Preserve Generics when generating JSON schema

I'm using jackson-module-jsonSchema and jsonschema2pojo API.

Brief explanation: I'm trying to json-schemify my server's Spring controller contract objects (objects that the controllers return and objects that they accept as parameters) and package them up to use with a packaged retrofit client in order to break the binary dependency between the client and server. The overall solution uses an annotation processor to read the Spring annotations on the controller and generate a retrofit client.

I've got it mostly working, but realized today I've got a problem where generic objects are part of the contract, e.g.

public class SomeContractObject<T> {
...
}

Of course, when I generate the schema for said object, the generic types aren't directly supported. So when I send it through the jsonschema2pojo api I end up with a class like so:

public class SomeContractObject {

}

So my question is simple but may have a non-trivial answer: Is there any way to pass that information through via the json schema to jsonschema2pojo?


Source: (StackOverflow)

Custom @JsonProperty Annotations

Consider the json schema:

{
    "type":"object",
    "$schema":"http://json-schema.org/draft-04/schema",
    "required":false,
    "properties":{
        "inventory":{
            "type":"object",
            "required":false,
            "properties":{
                "count":{
                    "type":"number",
                    "required":false
                }
            }
        }
    }
}

When using jsonschema2pojo, this generates a corresponding java object. Extracted from this is the following declaration for count (full class below):

@JsonProperty("count")
private Double count;

package com.test.json;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
    "count"
})
public class Inventory{

    /**
     * 
     */
    @JsonProperty("count")
    private Double count;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     * 
     * @return
     *     The count
     */
    @JsonProperty("count")
    public Double getCount() {
        return count;
    }

    /**
     * 
     * @param count
     *     The count
     */
    @JsonProperty("count")
    public void setCount(Double count) {
        this.arpu = count;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    @Override
    public boolean equals(Object other) {
        return EqualsBuilder.reflectionEquals(this, other);
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}

If the JSON interface changes, and count becomes countOfItems, both the JSON property annotation, AND the java variable name change, which affects getters and setters:

@JsonProperty("countOfItems")
private Double countOfItems;

@JsonProperty("countOfItems")
public Double getCountOfItems()

@JsonProperty("countOfItems")
public void setCountOfItems(Double countOfItems)

I would like to be able to customise the generated class so that implementing java code didn't have to change, i.e.:

@JsonProperty("countOfItems")
private Double count;

@JsonProperty("countOfItems")
public Double getCount()

@JsonProperty("countOfItems")
public void setCount(Double count)

Is this kind of feature supported using JSON schema and jsonschema2pojo? I can't find any information on how to do this on the json schema or jsonscema2pojo documentation.

Obviously this could be achieved by hand crafting the java object, but I'd rather keep using generated classes.


Source: (StackOverflow)

Make POJO class generated from JSON schema serializable

I am using the jsonschema2pojo-maven-plugin v0.4.7 to generate POJO classes from a JSON schema. A sample schema is as follows:

 "features": {
            "title": "Feature",
            "description": "Name and type of every feature in the model",
            "type": "array",
            "items": {
                "properties": {
                    "columnName": {
                        "description": "Name of the table column",
                        "type": "string"
                    },
                    "featureName": {
                        "description": "Name of that column's feature for the pipeline",
                        "type": "string"
                    },
                    "type": {
                        "description": "Type of the feature",
                        "type": "string"
                    }
                },
                "required": ["columnName", "type"]
            }

The resulting POJO class is somewhat as follows:

public class Feature {

    /**
     * Name of the table column
     * 
     */
    @JsonProperty("columnName")
    private String columnName;
    /**
     * Name of that column's feature for the pipeline
     * 
     */
    @JsonProperty("featureName")
    private String featureName;
    /**
     * Type of the feature
     * 
     */
    @JsonProperty("type")
    private String type;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     * Name of the table column
     * 
     * @return
     *     The columnName
     */
    @JsonProperty("columnName")
    public String getColumnName() {
        return columnName;
    }

    /**
     * Name of the table column
     * 
     * @param columnName
     *     The columnName
     */
    @JsonProperty("columnName")
    public void setColumnName(String columnName) {
        this.columnName = columnName;
    }

    /**
     * Name of that column's feature for the pipeline
     * 
     * @return
     *     The featureName
     */
    @JsonProperty("featureName")
    public String getFeatureName() {
        return featureName;
    }

    /**
     * Name of that column's feature for the pipeline
     * 
     * @param featureName
     *     The featureName
     */
    @JsonProperty("featureName")
    public void setFeatureName(String featureName) {
        this.featureName = featureName;
    }

    /**
     * Type of the feature
     * 
     * @return
     *     The type
     */
    @JsonProperty("type")
    public String getType() {
        return type;
    }

    /**
     * Type of the feature
     * 
     * @param type
     *     The type
     */
    @JsonProperty("type")
    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(columnName).append(featureName).append(type).append(additionalProperties).toHashCode();
    }

    @Override
    public boolean equals(Object other) {
        if (other == this) {
            return true;
        }
        if ((other instanceof Feature) == false) {
            return false;
        }
        Feature rhs = ((Feature) other);
        return new EqualsBuilder().append(columnName, rhs.columnName).append(featureName, rhs.featureName).append(type, rhs.type).append(additionalProperties, rhs.additionalProperties).isEquals();
    }

}

I am using one of the POJO classes generated from the Schema in a Spark Application which requires that this class implements Serializable to be able to use it a distributed setting.

I need the resulting class to implement Serialization like follows:

public class Feature implements Serializable {

}

Does anyone know a way to make a POJO class implement Serializable? Is their a JSON schema setting to make it serializable?

I have looked all over google with no luck. Thanks in advance.


Source: (StackOverflow)

json schema containing multiple independent types

Is there any example to show how a json schema can be written to include multiple independent objects in one file?

If its possible, is there any java library that can convert all of them to individual pojos and vice versa?


Source: (StackOverflow)

Jsonschema2pojo error with creating a list of objects with class name as "S"

I am trying to generate POJOs from a json schema.

Problem : If I have the class name as "s", it throws an error.

Error from plugin execution: Execution goal org.jsonschema2pojo:jsonschema2pojo-maven-plugin:0.4.0:generate failed: String index out of range: 0 -> [Help 1]

I have tried using the maven plugin as well as http://www.jsonschema2pojo.org/

<groupId>org.jsonschema2pojo</groupId>
    <artifactId>jsonschema2pojo-maven-plugin</artifactId>
    <version>0.4.0</version>

Both give errors while generating the pojos.

Other observations : It works for other letters.
If it is not an array type, then plain object works too, but not as an array

Small excerpt of the schema is as below :

 { 
  "type": "object",
  "id": "http://jsonschema.net/abc",
  "required": true,
  "description": "Some description",
  "properties": {
  "s": {
          "type": "array",
          "id": "http://jsonschema.net/abc/s",
          "required": true,
          "items": {
            "type": "object",
            "id": "http://jsonschema.net/price/abc/0/",
            "required": true,
            "description": "sales price object of an item",
            "properties": {
               "ip": {
                "type": "number",
                "id": "http://jsonschema.net/price/p/s/0/value",
                "required": true,
                "description": "some desc"
              }
             }
            }
    }
  }
}

Has someone faced a similar issue/known bug? Is there a workaround?


Source: (StackOverflow)

JSON to POJO conversion error for different types of values

While converting JSON data to POJO using Gson I get this error.

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 119

My JSON is :

{  
   "success":true,      
   "result":[  
      {  
         "htmlId":"edit_text_1",
         "value":"3",
         "contentType":"Snippet"
      },
      {  
         "htmlId":"edit_text_2",
         "value":[  
            {  
               "type":"HTML",
               "value":"<ul>\n<li>This is a text from the static editable content.</li>\n</ul>"
            },
            {  
               "type":"Text",
               "value":"- This is a text from the static editable content."
            }             ],
         "contentType":"Text"
      }
   ]
}

for each result the value type may differ. Sometimes it is a string value or an array.

Here's my pojo for results:

    private String htmlId;  
    private Object value = new ArrayList<Object>();
    private String contentType;

    public String getHtmlId() {
        return htmlId;
    }
    public void setHtmlId(String htmlId) {
        this.htmlId = htmlId;
    }
    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        if(value instanceof String)
        this.value = (List<String>)value;
    else if(value instanceof ArrayList)
        this.value = (ArrayList<MarketoTypeValue>)value;
    }

    public String getContentType() {
        return contentType;
    }
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

When there is no snippet type in the result, my code works fine. Tried with typecast, that did not help me either.

What can be the best way to handle such scenario?


Source: (StackOverflow)

Pojo to json schema v4 and vice versa via maven

I am trying to come up with a set of documents for one of our projects where there is a requirement to convert Java POJOs to JSON Schema 4 and sometimes JSON schema 4 back to POJOs. I couldn't find a maven plug-in that does both of it.

I was able to find https://github.com/wodzuu/JSONschema4-mapper for JSON Schema generation and https://github.com/joelittlejohn/jsonschema2pojo for PoJo generation.

I am sure it is a very common use case, so just writing to check what you folks used to get past this? Any inputs


Source: (StackOverflow)

JsonSchema2pojo doesnot generate POJO

I was given a pojo like below,

{

"id": "yyy",
"$schema": "http://json-schema.org/draft-04/schema#",
"packages": 
{
    "id": "#/packages",
    "description": "XXX",
    "type": "object",
    "properties": 
    {
        "xx": 
        {
            "description": "Total number of elements in the collection.",
            "type": "integer",
            "minimum": 1,
            "minLength": 1
        }
        ..............
        ...............         
    },
    "additionalProperties": false,
    "required": 
    [
        "xx",
        ...
        ... 
    ]
}
}

When trying to generate POJO with the Jsonschema2POJO I just see the package being created with no class files in it. Even no exceptions occur.

When I add a "properties" around the "packages" tag then it generates the pojo but if any other json references this json i get a "Path not present:packages" error and moreover it makes the schema invalid.

I want to understand if there is any limitation with the tool on the schema version? Or is there any modifications that has to be done in the jsons provided to make it work with the tool. Please suggest.


Source: (StackOverflow)

jsonschema2pojo-cli-0.4.13 dead in the water?

I'd like to create POJOs from a reasonably complex JSON schema that references types within itself, and the web interface has known issues doing this that are apparently fixed for offline use. I'm running on Win7, and the output from java -version is

  java version "1.7.0_79"
  Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
  Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)

The simplest offline mechanism is CLI, so I've downloaded the current version, extracted it to a folder (no spaces in the path, though I assume that's not an issue anyway) and tried getting the help output with jsonschema2pojo --help. I get

Exception in thread "main" java.lang.NoClassDefFoundError: org/jsonschema2pojo/GenerationConfig
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.getMainMethod(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.jsonschema2pojo.GenerationConfig
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 6 more

I'm in the same directory as the .jar files that came out of the package. I've also tried firing the appropriate .jar directly with java -jar jsonschema2pojo-cli-0.4.13.jar --help and get the same response. I've also tried running in an administrator shell just in case.

So at the moment it can't even start up, so there's little point trying to go further with it.

Is anyone else using this from the commandline? On Win7?


Source: (StackOverflow)