Json to xsd java

Jsons2xsd Save

Highly configurable converter from JSON-schema to XML-schema (XSD).

jsons2xsd

JSON-schema to XML schema converter written in Java.

Dependency

 com.ethlo.jsons2xsd jsons2xsd 2.3.0  

Snapshots

  sonatype-nexus-snapshots true  https://oss.sonatype.org/content/repositories/snapshots   

Usage

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

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

Источник

Convert from JSON to XML XSD-valid (with Apache Camel or Java)

I have a camel route that converts documents from JSON to XML; the XML must be valid regarding a schema which is defined in XSD. Currently, the conversion is done with camel-xmljson (and I have some custom java processing for the list types). The only thing that does not match the schema is the sequence of elements as the conversion changes the order to alphabetical because JSON per definition does not care about order. Since several document types that are subject to change need to be converted, it is important that the conversion and subsequent processing is as generic as possible (I’d like it to work with only XSD files and not with classes generated from XSD). So, I’m looking for a way to convert to the valid XML from JSON and XSD or a way to change the sequence of XML elements to match the definition from the XSD. Can anybody point something out?

Читайте также:  Таблицы

Hi welcome to the site. See this link for using XSLT to convert JSON to XML. This might be something that can point you in the right direction.stackoverflow.com/questions/13007280/…

Thanks. Unfortunately, it does not have a complete solution and I lack the XSLT expertise to do that.

1 Answer 1

JSON does not care about order in objects (key-value pairs) but it does in arrays, so maybe you should use JSON array where the order matters. Anyway, you can do that kind of JSON/XML transformation with standard XSLT 3.0 which introduced functions for JSON-to-XML and XML-to-JSON conversion. In Java, the SAXON XSLT library supports them (in all editions including the free one) since v9.7.

Here is an excerpt from a XSLT stylesheet applying transformation from JSON input (link to full XSLT ):

Then some sample code to use that XSLT from Java, assuming that SAXON XSLT >= 9.7 is on your classpath (this example takes input JSON as a String and outputs the result to System.out just for testing but you can adapt to handle other kinds of input/output with SAXON API easily):

import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.SaxonApiException; import net.sf.saxon.s9api.XdmAtomicValue; import net.sf.saxon.s9api.Xslt30Transformer; import net.sf.saxon.s9api.XsltExecutable; import net.sf.saxon.trace.XSLTTraceListener; . private static final XsltExecutable JSON_TO_XML_XSLT_EXEC; static < try < final Processor xsltProc = new Processor(false); JSON_TO_XML_XSLT_EXEC = xsltProc.newXsltCompiler().compile(new StreamSource(new File("/path/to/my/xslt/stylesheet/file")); >catch (final SaxonApiException e) < throw new RuntimeException("Cannot create XSLT processor for my stylesheet", e); >> private static void convertJsonToXml(final String inputJson, final Path outXmlFile) < final Xslt30Transformer xslt = JSON_TO_XML_XSLT_EXEC.load30(); /* * Line below is useful for debugging, esp. to see what the output from the json-to-xml function looks like before further processing. Else remove it. */ xslt.setTraceListener(new XSLTTraceListener()); try < xslt.setGlobalContextItem(new XdmAtomicValue(inputJson)); /* * Call default template "xsl:initial-template" */ xslt.callTemplate(null, xslt.newSerializer(System.out)); >catch (final SaxonApiException e) < throw new RuntimeException("Failed to apply XSLT", e); >> 

Источник

Генерация JSON-схемы из XSD с JAXB и Джексоном

В этой статье я продемонстрирую один из подходов к созданию схемы JSON из схемы XML (XSD). Представляя обзор подхода к созданию JSON-схемы из XML-схемы, эта статья также демонстрирует использование реализации JAXB (версия 2.2.12-b150331.1824 xjc в комплекте с JDK 9 [build 1.9.0-ea-b68]) и реализации связывания JSON / Java ( Джексон 2.5.4).

Шаги этого подхода для генерации JSON-схемы из XSD можно обобщить следующим образом:

  1. Примените компилятор JAXB xjc для генерации классов Java из XML-схемы (XSD).
  2. Примените Джексона для генерации JSON-схемы из сгенерированных JAXB Java-классов.

Генерация Java-классов из XSD с помощью JAXB’s xjc

Для целей этого обсуждения я буду использовать простой Food.xsd использованный в моем предыдущем сообщении в блоге «Нюанс JAXB: строка в сравнении с перечислением из перечисленной строки XSD с ограниченным доступом . Для удобства я воспроизвел здесь эту простую схему без комментариев XML, относящихся к предыдущему сообщению в блоге:

Food.xsd

Легко использовать инструмент командной строки xjc, предоставляемый реализацией JAXB, предоставленной JDK, для генерации классов Java, соответствующих этому XSD. Следующий снимок экрана показывает этот процесс с помощью команды:

xjc -d jaxb. \ Food.xsd

generatingJavaObjectsFromFoodXsdWithXjc

Эта простая команда генерирует классы Java, соответствующие предоставленному Food.xsd и помещает эти классы в указанный подкаталог «jaxb».

Генерация JSON из классов, сгенерированных JAXB, с Джексоном

Теперь, когда сгенерированные JAXB классы доступны, Джексон может быть применен к этим классам для генерации JSON из классов Java. На главной странице портала Джексон описан как «многоцелевая библиотека Java для обработки», которая «вдохновлена ​​качеством и разнообразием инструментов XML, доступных для платформы Java». Существование Jackson и аналогичных сред и библиотек, по-видимому, является одной из причин того, что Oracle отказалась от JEP 198 («Облегченный JSON API») с Java SE 9 . [Стоит отметить, что Java EE 7 уже имеет встроенную поддержку JSON с его реализацией JSR 353 («Java API для обработки JSON»), которая не связана с JEP 198).]

Одним из первых шагов применения Jackson для генерации JSON из наших сгенерированных JAXB Java-классов является получение и настройка экземпляра класса Jackson ObjectMapper . Один из подходов для достижения этой цели показан в следующем листинге кода.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Highly configurable converter from JSON-schema to XML-schema (XSD).

License

ethlo/jsons2xsd

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

JSON-schema to XML schema converter written in Java.

dependency> groupId>com.ethlo.jsons2xsdgroupId> artifactId>jsons2xsdartifactId> version>2.3.0version> dependency>
repositories> repository> id>sonatype-nexus-snapshotsid> snapshots> enabled>trueenabled> snapshots> url>https://oss.sonatype.org/content/repositories/snapshotsurl> repository> repositories>
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); >
< "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" ] > >
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();
final Config cfg = new Config.Builder() .nonJsonTypeMapping("date-time", XsdSimpleType.DATE_TIME) .nonJsonTypeMapping("int", XsdSimpleType.INT) . .build();

About

Highly configurable converter from JSON-schema to XML-schema (XSD).

Источник

Generate XSD programmatically in java

Is there any API to generate XSD programmatically in java. I need to generate XSD from Json-Schema ,I will read Json Schema and based on the elements i encounter during parsing need to create appropriate XSD elements. So if there is any API that can XSD elements it would help me in development process.

@dbank yes i have considered JAXB , but for using it we need to generate jaxb annotated classes before hand which is not possible since the json is dynimic , with diffferent tag names

1 Answer 1

I’ve used API’s such as XSOM and Xerces XML Schema to parse XSD’s, but their API’s don’t offer methods to programmatically generate XSD’s. (I suppose you could try to access their internal implementations to somehow generate an XSD, but that would be at your own risk and probably ill-advised.)

However, since an XSD is an XML document itself, you could use something like DOM through JAXP to programmatically create an XSD:

package dbank.so; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.XMLConstants; import org.w3c.dom.Document; import org.w3c.dom.Element; public class SchemaGenExample < private final static String NS_PREFIX = "xs:"; public static void main(String[] args) < try < DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element schemaRoot = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, NS_PREFIX+"schema"); doc.appendChild(schemaRoot); NameTypeElementMaker elMaker = new NameTypeElementMaker(NS_PREFIX, doc); Element idType = elMaker.createElement("simpleType", "idType"); schemaRoot.appendChild(idType); Element idTypeRestr = elMaker.createElement("restriction"); idTypeRestr.setAttribute("base", NS_PREFIX+"string"); idType.appendChild(idTypeRestr); Element idTypeRestrPattern = elMaker.createElement("pattern"); idTypeRestrPattern.setAttribute("value", "4"); idTypeRestr.appendChild(idTypeRestrPattern); Element itemType = elMaker.createElement("complexType", "itemType"); schemaRoot.appendChild(itemType); Element sequence = elMaker.createElement("sequence"); itemType.appendChild(sequence); Element itemIdElement = elMaker.createElement("element", "ItemId", "idType"); sequence.appendChild(itemIdElement); Element itemNameElement = elMaker.createElement("element", "ItemName", NS_PREFIX+"string"); sequence.appendChild(itemNameElement); Element itemElement = elMaker.createElement("element", "Item", "itemType"); schemaRoot.appendChild(itemElement); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty("indent-amount", "4"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource domSource = new DOMSource(doc); //to create a file use something like this: transformer.transform(domSource, new StreamResult(new File("mySchema.xsd"))); //to print to console use this: transformer.transform(domSource, new StreamResult(System.out)); > catch (FactoryConfigurationError | ParserConfigurationException | TransformerException e) < //handle exception e.printStackTrace(); >> /* * Class with methods to make it more convenient to create Element nodes with * namespace prefixed tagnames and with "name" and "type" attributes. */ private static class NameTypeElementMaker < private String nsPrefix; private Document doc; public NameTypeElementMaker(String nsPrefix, Document doc) < this.nsPrefix = nsPrefix; this.doc = doc; >public Element createElement(String elementName, String nameAttrVal, String typeAttrVal) < Element element = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, nsPrefix+elementName); if(nameAttrVal != null) element.setAttribute("name", nameAttrVal); if(typeAttrVal != null) element.setAttribute("type", typeAttrVal); return element; >public Element createElement(String elementName, String nameAttrVal) < return createElement(elementName, nameAttrVal, null); >public Element createElement(String elementName) < return createElement(elementName, null, null); >> > 

Which would create a mySchema.xsd that looks like this:

Which could be used for an XML file such as:

I’ve never worked with JSON Schema, but I suppose as you parse the JSON or iterate through your JSON data structure, you could sort out the logic to do something like the above example.

Источник

Оцените статью