XSD到JSON架构动态转换JAVA

时间:2017-02-17 13:18:56

标签: java xsd jaxb jsonschema

我有xsd架构,我需要提供json架构。我看到有可能使用JAXB和Jackson,但主要问题是我需要从xsd生成类,而且只能生成json模式。

我的目标是创建以下网站服务:

  1. 从服务器获取xsd
  2. 发送客户端json架构
  3. 接收json数据
  4. 将json数据转换为xml
  5. 验证xml - > XSD
  6. 我尝试过使用DynamicJAXBContext,ObjectMapper等,但我无法找到上面所写的所有步骤的解决方案:

    FileInputStream xsdInputStream = new FileInputStream("src/example/customer.xsd");
            DynamicJAXBContext jaxbContext = 
                DynamicJAXBContextFactory.createContextFromXSD(xsdInputStream, null, null, null);
    

    我还尝试生成.java文件并尝试将它们转换为架构:

    String outputDirectory = "..............\\src";
    SchemaCompiler sc = XJC.createSchemaCompiler();
    
    File schemaFile = new File("........\\Desktop\\SalesVal.xsd");
    InputSource is = new InputSource(schemaFile.toURI().toString());
    
    sc.parseSchema(is);
    S2JJAXBModel model = sc.bind();
    JCodeModel jCodeModel = model.generateCode(null, null);
    jCodeModel.build(new File(outputDirectory));
    for (com.sun.tools.xjc.api.Mapping m : model.getMappings()) {
        writeToStandardOutputWithDeprecatedJsonSchema(createJaxbObjectMapper(), m.getType()
                                                                                 .getTypeClass()
                                                                                 .fullName());
    

    static private void writeToStandardOutputWithDeprecatedJsonSchema(final ObjectMapper mapper,
                                                                      final String fullyQualifiedClassName) {
        try {
            final JsonSchema jsonSchema = mapper.generateJsonSchema(Class.forName(fullyQualifiedClassName));
            System.out.println(jsonSchema);
        } catch (ClassNotFoundException cnfEx) {
            System.err.println("Unable to find class " + fullyQualifiedClassName);
        } catch (JsonMappingException jsonEx) {
            System.err.println("Unable to map JSON: " + jsonEx);
        }
    }
    
    static private ObjectMapper createJaxbObjectMapper() {
        final ObjectMapper mapper = new ObjectMapper();
        final TypeFactory typeFactory = TypeFactory.defaultInstance();
        final AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(typeFactory);
        // make deserializer use JAXB annotations (only)
        mapper.getDeserializationConfig().with(introspector);
        // make serializer use JAXB annotations (only)
        mapper.getSerializationConfig().with(introspector);
        return mapper;
    }
    

0 个答案:

没有答案