Coder Social home page Coder Social logo

jsons2xsd's Introduction

jsons2xsd

Maven Central License: MIT Coverage Status Codacy Badge Build Status GitHub issues open

JSON-schema to XML schema converter written in Java.

Dependency

<dependency>
  <groupId>com.ethlo.jsons2xsd</groupId>
  <artifactId>jsons2xsd</artifactId>
  <version>2.3.0</version>
</dependency>

Snapshots

<repositories>
  <repository>
    <id>sonatype-nexus-snapshots</id>
    <snapshots>
      <enabled>true</enabled>
    </snapshots>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
  </repository>
</repositories>

Usage

try (final Reader r = ...)
{
  final Config cfg = new Config.Builder()
    .targetNamespace("http://example.com/myschema.xsd")
    .name("array")
    .build();
  final Document doc = Jsons2Xsd.convert(r, cfg);
}

Example input

{
  "type":"array",
  "items":{
    "type":"object",
    "properties":{
      "price":{
        "type":"number",
        "minimum":0
      },
      "name":{
        "type":"string",
        "minLength":5,
        "maxLength":32
      },
      "isExpired":{
        "default":false,
        "type":"boolean"
      },
      "manufactured":{
        "type":"string",
        "format":"date-time"
      }
    },
    "required":[
      "price",
      "name",
      "manufactured"
    ]
  }
}

Example output

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:x="http://example.com/myschema.xsd" elementFormDefault="qualified" targetNamespace="http://example.com/myschema.xsd">
  <complexType name="array">
    <sequence>
      <element name="price">
        <simpleType>
          <restriction base="decimal">
            <minInclusive value="0" />
          </restriction>
        </simpleType>
      </element>
      <element name="name">
        <simpleType>
          <restriction base="string">
            <minLength value="5" />
            <maxLength value="32" />
          </restriction>
        </simpleType>
      </element>
      <element minOccurs="0" name="isExpired" type="boolean" />
      <element name="manufactured" type="dateTime" />
    </sequence>
  </complexType>
</schema>

Support for non-standard types and formats

Ignore unknown JSON formats

final Config cfg = new Config.Builder()
    .ignoreUnknownFormats(true)
    ...
    .build();

Register custom JSON formats

final Config cfg = new Config.Builder()
    .customTypeMapping(JsonSimpleType.INTEGER, "int64", XsdSimpleType.LONG)
    .customTypeMapping(JsonSimpleType.INTEGER, "int32", XsdSimpleType.INT)
    .customTypeMapping(JsonSimpleType.STRING, "ext-ref", XsdSimpleType.STRING)
    ...
    .build();

Register non-JSON types

final Config cfg = new Config.Builder()
    .nonJsonTypeMapping("date-time", XsdSimpleType.DATE_TIME)
    .nonJsonTypeMapping("int", XsdSimpleType.INT)
    ...
    .build();

jsons2xsd's People

Contributors

chhsiao90 avatar dschrimpsher avatar ethlo avatar ilyanep avatar lbovet avatar skulasekar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

jsons2xsd's Issues

Exception in thread "main" java.lang.IllegalArgumentException: root should have type="object"

Running into multiple issues with the attached json. Can you please help me to create xsd. The exception i posted below was addressed by adding type=object but ran into properties issue. Then after fixing that ran into another issue. The attached json is generated by Swagger tool.

Exception in thread "main" java.lang.IllegalArgumentException: root should have type="object"
at com.ethlo.schematools.jsons2xsd.Assert.isTrue(Assert.java:13)
at com.ethlo.schematools.jsons2xsd.Jsons2Xsd.convert(Jsons2Xsd.java:81)
at com.ethlo.schematools.jsons2xsd.TestJsonToXsd.main(TestJsonToXsd.java:21)

offers.txt

Allow rendering of arrays unwrapped

This JSON Schema:

    "Foo": {
      "title": "Foo",
      "type": "object",
      "properties": {
        "uris": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/Bar"
          }
        }
      }
    }

Yields this XSD:

   <complexType name="Foo">
      <sequence>
         <element minOccurs="0" name="uris">
            <complexType>
               <sequence>
                  <element maxOccurs="unbounded"
                           minOccurs="0"
                           name="Bar"
                           type="x:Bar"/>
               </sequence>
            </complexType>
         </element>
      </sequence>
   </complexType>

But ideally I'd have an option to make it render:

   <complexType name="Foo">
      <sequence>
         <element minOccurs="0" name="uris" type="x:Bar"/>
      </sequence>
   </complexType>

This would be more in line with both how protobuf's XML renderer library renders repeated elements and with what happens when I use Google's library to render a message into a JSON string and then use Jackson's XML data format to render that to XML.

Support long numbers

This JSON Schema:

        "version": {
          "type": "integer",
          "minimum": -9007199254740991,
          "maximum": 9007199254740991
        },

Is turned into this XSD:

         <element name="version">
            <simpleType>
               <restriction base="int">
                  <minInclusive value="1"/>
                  <maxInclusive value="-1"/>
               </restriction>
            </simpleType>
         </element>

Instead, I believe you could use the XML type long and use Longs in the java that reads in those mins and maxes.

Array type as object properties not supported

I tried to use your tool with this sample below , I just changed the price number property by prices , an array of object with price property

{ "type":"array", "items":{ "type":"object", "properties":{ "prices":{ "type":"array", "items":{ "type":"object", "properties":{ "price":{ "type":"number" } }, "required":["price"] } }, "name":{ "type":"string", "minLength":5, "maxLength":32 }, "isExpired":{ "default":false, "type":"boolean" }, "manufactured":{ "type":"string", "format":"date-time" } }, "required":[ "prices", "name", "manufactured" ] } }

If I try to convert this schema in xsd with validateXsdSchema set to true i have this error

{"status":400,"message":"org.xml.sax.SAXParseException; lineNumber: 8; columnNumber: 36; Unexpected <complexType> appears at line 8 column 36","error":"java.lang.IllegalArgumentException"}

If I try to convert this schema in xsd with validateXsdSchema set to false i have this result

<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:x="http://example.com/myschema.xsd" elementFormDefault="qualified" targetNamespace="http://example.com/myschema.xsd"> <complexType name="array"> <sequence> <element name="prices"> <complexType> <sequence> <element maxOccurs="unbounded" minOccurs="0"> <complexType name=""> <sequence> <element name="price" type="decimal"/> </sequence> </complexType> </element> </sequence> </complexType> </element> <element name="name"> <simpleType> <restriction base="string"> <minLength value="5"/> <maxLength value="32"/> </restriction> </simpleType> </element> <element minOccurs="0" name="isExpired" type="boolean"/> <element name="manufactured" type="dateTime"/> </sequence> </complexType> </schema>

I think this result comport misplaced complexType whitout name attribute.
Am I missing something?

Creating XSD from non-object type

Hi

First of all I want to say thanks for a great tool.

I'm getting java.lang.IllegalArgumentException: root should have type="object" when using a schema that is not starting with object such as.

{
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "price": {
                "type": "number"
            },
            "name": {
                "type": "string"
            },
            "isExpired": {
                "default": false,
                "type": "boolean"
            }
        }
    }
}

Am I doing something wrong here or is this a bug?

Thanks
Björn

2.3.0 release didn't update the pom or readme for the new version

The pom.xml has the version at the previous 2.2.1 and the readme.md uses the example for 2.2.0 (in case someone is quickly copy/pasting the maven section.

The question is whether the current master was built and replaced the original 2.2.1 release. I know artifactory only allows publishing a single release version and if you have a mistake you need to bump the version and republish.

Build Failure

Hi, I'm getting this build failure with Maven, can anybody help please? I am new to this whole Maven thing btw.

Environment:
Windows 10
OpenJDK 11.0.1
JRE 1.8.0_192
Apache Maven 3.5.4

Error:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------

Exception in thread "main" java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:513)
        at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:525)
Caused by: java.lang.RuntimeException: Class java/util/UUID could not be instrumented.
        at org.jacoco.agent.rt.internal_8ff85ea.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:140)
        at org.jacoco.agent.rt.internal_8ff85ea.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:101)
        at org.jacoco.agent.rt.internal_8ff85ea.PreMain.createRuntime(PreMain.java:55)
        at org.jacoco.agent.rt.internal_8ff85ea.PreMain.premain(PreMain.java:47)
        ... 6 more
Caused by: java.lang.NoSuchFieldException: $jacocoAccess
        at java.base/java.lang.Class.getField(Class.java:2000)
        at org.jacoco.agent.rt.internal_8ff85ea.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:138)
        ... 9 more
FATAL ERROR in native method: processing of -javaagent failed

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 20.145 s
[INFO] Finished at: 2018-10-20T10:52:08+11:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test (default-test) on project jsons2xsd: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test failed: The forked VM terminated without properly saying goodbye. VM crash or System.exit called?
[ERROR] Command was cmd.exe /X /C ""C:\Program Files\Java\jdk-11.0.1\bin\java" -javaagent:C:\\Users\\Aaron\\.m2\\repository\\org\\jacoco\\org.jacoco.agent\\0.7.9\\org.jacoco.agent-0.7.9-runtime.jar=destfile=C:\\Users\\Aaron\\DevFU\\jsons2xsd\\target\\jacoco.exec -jar C:\Users\Aaron\DevFU\jsons2xsd\target\surefire\surefirebooter15504269283019043524.jar C:\Users\Aaron\DevFU\jsons2xsd\target\surefire\surefire14852525687548396943tmp C:\Users\Aaron\DevFU\jsons2xsd\target\surefire\surefire_06187183096460743166tmp"
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException

47 compile errors only

Using java JDK-9.04 on Windows 10

C:\repos\SRSFormatService\jsons2xsd-master\jsons2xsd-master\src\main\java\com\ethlo\jsons2xsd>"C:\Program Files\Java\jdk-9.0.4\bin\javac" *.java
Jsons2Xsd.java:45: error: package com.fasterxml.jackson.databind does not exist
import com.fasterxml.jackson.databind.JsonNode;
^
Jsons2Xsd.java:46: error: package com.fasterxml.jackson.databind does not exist
import com.fasterxml.jackson.databind.ObjectMapper;
^
Jsons2Xsd.java:47: error: package com.fasterxml.jackson.databind.node does not exist
import com.fasterxml.jackson.databind.node.ArrayNode;
^
Jsons2Xsd.java:121: error: cannot find symbol
private static final ObjectMapper mapper = new ObjectMapper();
^
symbol: class ObjectMapper
location: class Jsons2Xsd
Jsons2Xsd.java:171: error: cannot find symbol
private static void handleArraySchema(Config cfg, JsonNode rootNode, Element schemaRoot, Set neededElements)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:204: error: cannot find symbol
private static void handleObjectSchema(Config cfg, final JsonNode rootNode, final Element schemaRoot, final Set neededElements)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:231: error: cannot find symbol
private static void doIterateDefinitions(Set neededElements, Element elem, JsonNode node, Config cfg)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:277: error: cannot find symbol
private static void handleObject(Set neededElements, String key, Element elem, JsonNode node, Config cfg)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:295: error: cannot find symbol
private static void handleChoice(Set neededElements, Element elem, ArrayNode oneOf, Config cfg)
^
symbol: class ArrayNode
location: class Jsons2Xsd
Jsons2Xsd.java:312: error: cannot find symbol
private static void doIterate(Set neededElements, Element elem, JsonNode node, List requiredList, Config cfg)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:337: error: cannot find symbol
private static void doIterateSingle(Set neededElements, String name, JsonNode val, Element elem, boolean required, Config cfg)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:387: error: cannot find symbol
private static void handleReference(Set neededElements, Element nodeElem, JsonNode val, Config cfg)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:404: error: cannot find symbol
private static void handleString(Element nodeElem, JsonNode val)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:437: error: cannot find symbol
private static void handleEnum(Element nodeElem, JsonNode val)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:452: error: cannot find symbol
private static void handleNumber(Element nodeElem, String xsdType, JsonNode jsonNode)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:478: error: cannot find symbol
private static void handleArray(Set neededElements, Element nodeElem, JsonNode jsonNode, Config cfg)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:488: error: cannot find symbol
private static void handleArrayElements(Set neededElements, JsonNode jsonNode, final JsonNode arrItems, final String arrayXsdType, final Element arrElem, Config cfg)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:488: error: cannot find symbol
private static void handleArrayElements(Set neededElements, JsonNode jsonNode, final JsonNode arrItems, final String arrayXsdType, final Element arrElem, Config cfg)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:513: error: cannot find symbol
private static String determineXsdType(String key, JsonNode node)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:537: error: cannot find symbol
private static Integer getIntVal(JsonNode node, String attribute)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:553: error: cannot find symbol
private static List getRequiredList(JsonNode jsonNode)
^
symbol: class JsonNode
location: class Jsons2Xsd
XmlUtil.java:56: error: package com.sun.xml.xsom.parser does not exist
import com.sun.xml.xsom.parser.XSOMParser;
^
Jsons2Xsd.java:121: error: cannot find symbol
private static final ObjectMapper mapper = new ObjectMapper();
^
symbol: class ObjectMapper
location: class Jsons2Xsd
Jsons2Xsd.java:130: error: cannot find symbol
final JsonNode rootNode = mapper.readTree(jsonSchema);
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:150: error: cannot find symbol
JsonNode definitions;
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:153: error: cannot find symbol
final JsonNode definitionsRootNode = mapper.readTree(definitionSchema);
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:173: error: cannot find symbol
final JsonNode items = rootNode.path(FIELD_ITEMS);
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:206: error: cannot find symbol
JsonNode properties;
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:233: error: cannot find symbol
final Iterator<Entry<String, JsonNode>> iter = node.fields();
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:236: error: cannot find symbol
final Entry<String, JsonNode> entry = iter.next();
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:238: error: cannot find symbol
final JsonNode val = entry.getValue();
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:279: error: cannot find symbol
final JsonNode properties = node.get(FIELD_PROPERTIES);
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:290: error: cannot find symbol
final ArrayNode oneOf = (ArrayNode) node.get("oneOf");
^
symbol: class ArrayNode
location: class Jsons2Xsd
Jsons2Xsd.java:290: error: cannot find symbol
final ArrayNode oneOf = (ArrayNode) node.get("oneOf");
^
symbol: class ArrayNode
location: class Jsons2Xsd
Jsons2Xsd.java:299: error: cannot find symbol
for (JsonNode e : oneOf)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:302: error: cannot find symbol
final JsonNode refs = e.get(JSON_REF);
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:316: error: cannot find symbol
final Iterator<Entry<String, JsonNode>> fieldIter = node.fields();
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:319: error: cannot find symbol
final Entry<String, JsonNode> entry = fieldIter.next();
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:321: error: cannot find symbol
final JsonNode val = entry.getValue();
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:328: error: cannot find symbol
for (JsonNode entry : node)
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:331: error: cannot find symbol
final JsonNode val = entry;
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:389: error: cannot find symbol
final JsonNode refs = val.get(JSON_REF);
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:443: error: cannot find symbol
final JsonNode enumNode = val.get("enum");
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:480: error: cannot find symbol
final JsonNode arrItems = jsonNode.path("items");
^
symbol: class JsonNode
location: class Jsons2Xsd
Jsons2Xsd.java:561: error: cannot find symbol
for (JsonNode requiredField : jsonNode.withArray(FIELD_REQUIRED))
^
symbol: class JsonNode
location: class Jsons2Xsd
XmlUtil.java:117: error: cannot find symbol
XSOMParser parser = new XSOMParser(factory);
^
symbol: class XSOMParser
location: class XmlUtil
XmlUtil.java:117: error: cannot find symbol
XSOMParser parser = new XSOMParser(factory);
^
symbol: class XSOMParser
location: class XmlUtil
47 errors

C:\repos\SRSFormatService\jsons2xsd-master\jsons2xsd-master\src\main\java\com\ethlo\jsons2xsd>

How to convert to XML Attributes in XSD ?

I am trying to convert a JSON Schema to XSD. I need few entities to come as attributes but they are coming as elements? How can i achieve that? Is there something to specify as part of JSON Schema or something at Config level?

Actual : <element name="ABCD" type="string"/>
Expected: <attribute name="ABCD" type="xs:string"/>

Return null when using your example

I'm using the following code to convert json schema to xsd:
InputStream inputStream = new ClassPathResource("The-path-to-the-file").getInputStream();
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)))
{
final Config cfg = new Config.Builder().targetNamespace("http://example.com/myschema.xsd").name("array").build();
final Document doc = Jsons2Xsd.convert(reader, cfg);
}
The inputStream has the content that you write in your example:
{
"type":"array",
"items":{
"type":"object",
"properties":{
"price":{
"type":"number",
"minimum":0
},
"name":{
"type":"string",
"minLength":5,
"maxLength":32
},
"isExpired":{
"default":false,
"type":"boolean"
},
"manufactured":{
"type":"string",
"format":"date-time"
}
},
"required":[
"price",
"name",
"manufactured"
]
}
}

However, the returned variable "doc" is null !

Generates invalid XSD for some input

Hi Team,
First of all I would like to thank your team.

I am not sure whether its bug or not, i just wanted notify my issue.. as i hv attached my "input_json" and "expected_json", the output i am not getting as expected, please help to do the needful.

input_json.txt
expected_json.txt

and also my requirement is if type not found the default to object - to do this i hv made changes to code at line no 526 in Jsons2Xsd class

else if(jsonType == null && jsonFormat==null ) {
return XsdComplexType.OBJECT_VALUE;
}

invalid_output.txt
this is the output presently i am getting which is invalid and i validated -http://www.utilities-online.info/xsdvalidation

Note - line no's to look in attached files:

  1. input_json - 40
  2. expected_json - start from 25
  3. invalid_output - 35

Thank you.

Not work for definitions of non-object type

Hello,

Thanks for sharing this project. I am using it. I found this lib not support definitions of non-object type, like

"definitions": {
   "GUID": {
    "pattern": "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$",
    "type": "string"
  },
  "TestEnum": {
    "enum": [ "A", "B", "C", "D" ]
  }
}

I have fixed it to make the lib work for my project, like

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Other Definition",
    "type": "object",

    "definitions": {
        "GUID": {
            "pattern": "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$",
            "type": "string"
        },
        "TestEnum": {
            "enum": [
                "A",
                "B",
                "C",
                "D"
            ]
        },
        "Item": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
                "Value": {
                    "$ref": "#/definitions/GUID"
                },
                "Type": {
                    "$ref": "#/definitions/TestEnum"
                }
            },
            "required": [
                "Value",
                "Type"
            ]
        },
        "TestArray": {
            "type": "array",
            "items": { "$ref": "#/definitions/Item" }
        }
    },

    "properties": {
        "content": { "$ref": "#/definitions/TestArray" }
    },

    "required": [
        "content"
    ]
}
<?xml version="1.0" encoding="UTF-8"?><schema xmlns:otherdefinition="http://cableapi.cablelabs.com/schemas/v1/OtherDefinition" elementFormDefault="qualified" targetNamespace="http://cableapi.cablelabs.com/schemas/v1/OtherDefinition" xmlns="http://www.w3.org/2001/XMLSchema">
  <element name="OtherDefinition" type="otherdefinition:OtherDefinition"/>
  <simpleType name="TestEnum">
    <restriction base="string">
      <enumeration value="A"/>
      <enumeration value="B"/>
      <enumeration value="C"/>
      <enumeration value="D"/>
    </restriction>
  </simpleType>
  <complexType name="Item">
    <sequence>
      <element name="Value">
        <simpleType>
          <restriction base="string">
            <pattern value="^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"/>
          </restriction>
        </simpleType>
      </element>
      <element name="Type" type="otherdefinition:TestEnum"/>
    </sequence>
  </complexType>
  <complexType name="OtherDefinition">
    <sequence>
      <element name="Content">
        <complexType>
          <sequence>
            <element maxOccurs="unbounded" minOccurs="0" name="Item" type="otherdefinition:Item"/>
          </sequence>
        </complexType>
      </element>
    </sequence>
  </complexType>
</schema>

If you'd like, I can send a pull request.

Best Regards,
Heng

Please remove hardcodings of "definitions" in Jsons2Xsd and allow support for 2019_09 "$defs"

Please remove hardcodings of "definitions" in Jsons2Xsd and allow support for 2019_09 "$defs"

Presently you have use constant JSON_DEFINITIONS which is not used properly everywhere like #/definitions which should be made to #/ + JSON_DEFINITIONS

Apart from this I propose you also support 2019_09 "$defs" and check for both if need be or allow uses to configure one or the other as input

Thanks in advance for doing this minor change quickly so that user dont have to hack or fork

Configuration to control array element names

Currently, array elements are named after the JSON schema name.
In order to control or avoid using type names in the XML instances, it should be possible to choose how these elements are named.

Proposal
Config.mapArrayElementNames(Function<String,String> mapper)
default is the identity function

Examples
If one wants names in camelCase:
cfg.mapArrayElementNames(name -> name.substring(0, 1).toLowerCase() + name.substring(1))

If one wants to use "item" everywhere:
cfg.mapArrayElementNames(name -> "item")

You can assign to me. It will be shortly done and can be included in 2.2.0.

Test using your example JSON fails

Hello,

I'm testing your code using your example. Here is my main method:
public static void main(String[] args) {
try {
InputStream inputStream = new FileInputStream("C:\projects\acp.convertJsonToXsd\src\testSchema.json");
Reader inputStreamReader = new InputStreamReader(inputStream);
final String targetNameSpaceUri = "http://my.example.com/ns";
final OuterWrapping wrapping = OuterWrapping.TYPE;
final String name = "mySpecialType";
final Document xsdDocument = Jsons2Xsd.convert(inputStreamReader, targetNameSpaceUri, wrapping, name);

        System.out.println(xsdDocument.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

The json is the example you provide.

It seems to error on the required field for email.

Here is the output / exception:
In PROP
In PROP
Exception in thread "main" java.lang.IllegalArgumentException: required must have type: string array
at com.ethlo.schematools.jsons2xsd.Assert.isTrue(Assert.java:13)
at com.ethlo.schematools.jsons2xsd.Jsons2Xsd.getRequiredList(Jsons2Xsd.java:397)
at com.ethlo.schematools.jsons2xsd.Jsons2Xsd.handleObject(Jsons2Xsd.java:281)
at com.ethlo.schematools.jsons2xsd.Jsons2Xsd.doIterateSingle(Jsons2Xsd.java:213)
at com.ethlo.schematools.jsons2xsd.Jsons2Xsd.doIterate(Jsons2Xsd.java:174)
at com.ethlo.schematools.jsons2xsd.Jsons2Xsd.convert(Jsons2Xsd.java:101)
at acp.convertJsonToXsd.ConvertJsonToXsd.main(ConvertJsonToXsd.java:22)

Please advise. Thank you!

Anita

Type mapping does not include type=integer, format=int64

Hey,
I'm just testing out your project. Thanks for the great lib!
Unfortunately, I'm running into some issues: The first json I want to convert throws an IllegalArgumentException. Looking into your code, the problem seems to be the type of this object which does not exist in your code. The json is the following:
{"User": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"key": {
"type": "string"
}
}
}
}
Am I missing something or is this combination not covered in your lib?

Thank you already for your reply!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.