Validate JSON against XML Schema (XSD)
Asked Answered
E

3

18

Is it possible to validate JSON with an XSD in Java? I have an application where I receive JSON response, and I would like to validate it against existing XSD. Another part of my application uses XML, which is why it would be easiest if they both could validate against the existing XSD.

Effects answered 22/3, 2016 at 11:17 Comment(2)
You'd have to convert it to xml i think... urgh. Just use JSON everywhere :-)Lilas
for json it's better to generate a json shema similar to xsd and validate against it. There are third-party libs to validate json against schema, maybe exists such for Java.Tega
S
25

No, XML Schema (XSD) is for validating XML; to validate JSON, see JSON Schema.

I recommend generating schemas by hand for full understanding and full control over the constraints. However, here are some automated tools that can jumpstart the process:

Related and also very useful:

  • To parse from XML to JSON (unmarshal) or serialize JSON to XML (marshal), see JSONIX.
  • For a list of implementations, including validators in various languages, see JSON-Schema Implementations.
Semmes answered 22/3, 2016 at 13:12 Comment(5)
Thank you. Is it easy to validate against the JSON schema?Effects
Generally, sure. See Validators section of JSON-Schema Implementations.Semmes
Can you expand on why you can't use XSD for JSON? I imagine you could just convert the JSON to XML then check that XML against the XSD. Other than raw text in XML, JSON and XML are just elements which have attributes and child elements.Consulate
@ubiquibacon: Of course any XML can be validated with XSD, including XML that was automatically converted from JSON using the methods I mentioned in the answer.Semmes
The biggest problem with using JSONIX is my JSON schema property names have @,#, and - prefixing them, so creating an XML Schema from them seems unlikely. We already have a perfectly good XML Schema, so the task becomes converting JSON to DOM.Regnant
C
3

No, the standards are different between the two.

But if you really want to rely on the xsd for validating, Jsonix Schema Compiler can help you generate a JSON Schema to validate your json from your XML Schema.

Cowman answered 22/3, 2016 at 11:52 Comment(1)
JSON schema is not a standard, so I can’t rely on it.Regnant
R
-1

Yes, you can validate JSON with XML Schema, if you convert it to DOM:

https://github.com/coderextreme/x3dschema

See Validate.java (validator) and X3DJSONLD.java (converter).

Regnant answered 15/12, 2023 at 22:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.