{"id":265,"date":"2018-12-17T08:06:46","date_gmt":"2018-12-17T08:06:46","guid":{"rendered":"https:\/\/jan.schnasse.org\/blog\/?p=265"},"modified":"2018-12-17T08:06:46","modified_gmt":"2018-12-17T08:06:46","slug":"converting-xml-to-json","status":"publish","type":"post","link":"https:\/\/jan.schnasse.org\/blog\/2018\/12\/17\/converting-xml-to-json\/","title":{"rendered":"Converting XML to JSON"},"content":{"rendered":"<p><strong>You can use standard tools for it<\/strong><\/p>\n<p><strong>1.<\/strong> Use the tool <code>xjc<\/code> from your jdk to <a href=\"https:\/\/stackoverflow.com\/questions\/11463231\/how-to-generate-jaxb-classes-from-xsd\">generate Java classes from schema<\/a><\/p>\n<p>Since <code>Java 9<\/code> you must explicitly add JAXB as module with <code>\u2013add-modules java.se.ee<\/code> See: <a href=\"https:\/\/stackoverflow.com\/questions\/43574426\/how-to-resolve-java-lang-noclassdeffounderror-javax-xml-bind-jaxbexception-in-j\">How to resolve java.lang.NoClassDefFoundError: javax\/xml\/bind\/JAXBException in Java 9<\/a><\/p>\n<p>Since Java 11 you have to download <code>xjc<\/code> in an extra step from <a href=\"https:\/\/javaee.github.io\/jaxb-v2\/\" rel=\"nofollow noreferrer\">https:\/\/javaee.github.io\/jaxb-v2\/<\/a><\/p>\n<p><strong>2.<\/strong> Read in as <code>XML<\/code> write out as <code>JSON<\/code> using <a href=\"https:\/\/mvnrepository.com\/artifact\/com.fasterxml.jackson.core\/jackson-core\/2.8.1\" rel=\"nofollow noreferrer\">Jackson<\/a><\/p>\n<p><strong>Example<\/strong><\/p>\n<p>With <a href=\"https:\/\/schema.datacite.org\/meta\/kernel-4.1\/metadata.xsd\" rel=\"nofollow noreferrer\">https:\/\/schema.datacite.org\/meta\/kernel-4.1\/metadata.xsd<\/a><\/p>\n<p><strong>1. Use the tool <code>xjc<\/code> from your jdk<\/strong><\/p>\n<p>In my example I will use a fairly complex example based on datacite schemas.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">\/path\/to\/jdk\/bin\/xjc -d \/path\/to\/java\/project \\\n-p stack24174963.datacite \\\n https:\/\/schema.datacite.org\/meta\/kernel-4.1\/metadata.xsd<\/pre>\n<p>This will reply with<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">parsing a schema...\ncompiling a schema...\nstack24174963\/datacite\/Box.java\nstack24174963\/datacite\/ContributorType.java\nstack24174963\/datacite\/DateType.java\nstack24174963\/datacite\/DescriptionType.java\nstack24174963\/datacite\/FunderIdentifierType.java\nstack24174963\/datacite\/NameType.java\nstack24174963\/datacite\/ObjectFactory.java\nstack24174963\/datacite\/Point.java\nstack24174963\/datacite\/RelatedIdentifierType.java\nstack24174963\/datacite\/RelationType.java\nstack24174963\/datacite\/Resource.java\nstack24174963\/datacite\/ResourceType.java\nstack24174963\/datacite\/TitleType.java\nstack24174963\/datacite\/package-info.java<\/pre>\n<p>If you look into <span style=\"font-family: andale mono, monospace;\">Resource.Creator<\/span> and <span style=\"font-family: andale mono, monospace;\">Resource.Contributor<\/span> you will see that the member variables <span style=\"font-family: andale mono, monospace;\">givenName<\/span> and <span style=\"font-family: andale mono, monospace;\">familyName<\/span> are not correctly typed. Change their type from <span style=\"font-family: andale mono, monospace;\">Object<\/span> to <span style=\"font-family: andale mono, monospace;\">String<\/span>, also apply your changes to the corresponding getter and setter methods!<\/p>\n<p><strong>2. Read in as <code>XML<\/code> write out as <code>JSON<\/code> using Jackson<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">import com.fasterxml.jackson.databind.ObjectMapper;\n  import com.fasterxml.jackson.databind.SerializationFeature;\n\n  import stack24174963.datacite.Resource;\n\n  public class HowToXmlToJsonWithSchema {\n    @Test\n    public void readXmlAndConvertToSchema() throws Exception {\n        String example = \"schemas\/datacite\/kernel-4.1\/example\/datacite-example-complicated-v4.1.xml\";\n        try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(example)) {\n            Resource resource = JAXB.unmarshal(in, Resource.class);\n            System.out.println(asJson(resource));\n        }\n    }\n\n    private String asJson(Object obj) throws Exception {\n        StringWriter w = new StringWriter();\n        new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true).writeValue(w, obj);\n        String result = w.toString();\n        return result;\n    }\n  }<\/pre>\n<p>Prints:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\n  \"identifier\" : {\n    \"value\" : \"10.5072\/testpub\",\n    \"identifierType\" : \"DOI\"\n  },\n  \"creators\" : {\n    \"creator\" : [ {\n      \"creatorName\" : {\n        \"value\" : \"Smith, John\",\n        \"nameType\" : \"PERSONAL\"\n      },\n      \"givenName\" : \"John\",\n      \"familyName\" : \"Smith\",\n      \"nameIdentifier\" : [ ],\n      \"affiliation\" : [ ]\n    }, {\n      \"creatorName\" : {\n        \"value\" : \"\u3064\u307e\u3089\u306a\u3044\u3082\u306e\u3067\u3059\u304c\",\n        \"nameType\" : null\n      },\n      \"givenName\" : null,\n      \"familyName\" : null,\n      \"nameIdentifier\" : [ {\n        \"value\" : \"0000000134596520\",\n        \"nameIdentifierScheme\" : \"ISNI\",\n        \"schemeURI\" : \"http:\/\/isni.org\/isni\/\"\n      } ],\n      \"affiliation\" : [ ]\n    } ]\n  },\n  \"titles\" : {\n    \"title\" : [ {\n      \"value\" : \"W\u0142a\u015bciwo\u015bci rzutowa\u0144 podprzestrzeniowych\",\n      \"titleType\" : null,\n      \"lang\" : \"pl\"\n    }, {\n      \"value\" : \"Translation of Polish titles\",\n      \"titleType\" : \"TRANSLATED_TITLE\",\n      \"lang\" : \"en\"\n    } ]\n  },\n  \"publisher\" : \"Springer\",\n  \"publicationYear\" : \"2010\",\n  \"resourceType\" : {\n    \"value\" : \"Monograph\",\n    \"resourceTypeGeneral\" : \"TEXT\"\n  },\n  \"subjects\" : {\n    \"subject\" : [ {\n      \"value\" : \"830 German &amp; related literatures\",\n      \"subjectScheme\" : \"DDC\",\n      \"schemeURI\" : null,\n      \"valueURI\" : null,\n      \"lang\" : \"en\"\n    }, {\n      \"value\" : \"Polish Literature\",\n      \"subjectScheme\" : null,\n      \"schemeURI\" : null,\n      \"valueURI\" : null,\n      \"lang\" : \"en\"\n    } ]\n  },\n  \"contributors\" : {\n    \"contributor\" : [ {\n      \"contributorName\" : {\n        \"value\" : \"Doe, John\",\n        \"nameType\" : \"PERSONAL\"\n      },\n      \"givenName\" : \"John\",\n      \"familyName\" : \"Doe\",\n      \"nameIdentifier\" : [ {\n        \"value\" : \"0000-0001-5393-1421\",\n        \"nameIdentifierScheme\" : \"ORCID\",\n        \"schemeURI\" : \"http:\/\/orcid.org\/\"\n      } ],\n      \"affiliation\" : [ ],\n      \"contributorType\" : \"DATA_COLLECTOR\"\n    } ]\n  },\n  \"dates\" : null,\n  \"language\" : \"de\",\n  \"alternateIdentifiers\" : {\n    \"alternateIdentifier\" : [ {\n      \"value\" : \"937-0-4523-12357-6\",\n      \"alternateIdentifierType\" : \"ISBN\"\n    } ]\n  },\n  \"relatedIdentifiers\" : {\n    \"relatedIdentifier\" : [ {\n      \"value\" : \"10.5272\/oldertestpub\",\n      \"resourceTypeGeneral\" : null,\n      \"relatedIdentifierType\" : \"DOI\",\n      \"relationType\" : \"IS_PART_OF\",\n      \"relatedMetadataScheme\" : null,\n      \"schemeURI\" : null,\n      \"schemeType\" : null\n    } ]\n  },\n  \"sizes\" : {\n    \"size\" : [ \"256 pages\" ]\n  },\n  \"formats\" : {\n    \"format\" : [ \"pdf\" ]\n  },\n  \"version\" : \"2\",\n  \"rightsList\" : {\n    \"rights\" : [ {\n      \"value\" : \"Creative Commons Attribution-NoDerivs 2.0 Generic\",\n      \"rightsURI\" : \"http:\/\/creativecommons.org\/licenses\/by-nd\/2.0\/\",\n      \"lang\" : null\n    } ]\n  },\n  \"descriptions\" : {\n    \"description\" : [ {\n      \"content\" : [ \"\\n      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea\\n      takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores\\n      et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.\\n    \" ],\n      \"descriptionType\" : \"ABSTRACT\",\n      \"lang\" : \"la\"\n    } ]\n  },\n  \"geoLocations\" : null,\n  \"fundingReferences\" : null\n}<\/pre>\n<p>For XML input:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"xml\">&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n  &lt;resource xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xmlns=\"http:\/\/datacite.org\/schema\/kernel-4\" xsi:schemaLocation=\"http:\/\/datacite.org\/schema\/kernel-4 http:\/\/schema.datacite.org\/meta\/kernel-4.1\/metadata.xsd\"&gt;\n    &lt;identifier identifierType=\"DOI\"&gt;10.5072\/testpub&lt;\/identifier&gt;\n    &lt;creators&gt;\n      &lt;creator&gt;\n        &lt;creatorName nameType=\"Personal\"&gt;Smith, John&lt;\/creatorName&gt;\n        &lt;givenName&gt;John&lt;\/givenName&gt;\n        &lt;familyName&gt;Smith&lt;\/familyName&gt;\n      &lt;\/creator&gt;\n      &lt;creator&gt;\n        &lt;creatorName&gt;\u3064\u307e\u3089\u306a\u3044\u3082\u306e\u3067\u3059\u304c&lt;\/creatorName&gt;\n        &lt;nameIdentifier nameIdentifierScheme=\"ISNI\" schemeURI=\"http:\/\/isni.org\/isni\/\"&gt;0000000134596520&lt;\/nameIdentifier&gt;\n      &lt;\/creator&gt;\n    &lt;\/creators&gt;\n    &lt;titles&gt;\n      &lt;title xml:lang=\"pl\"&gt;W\u0142a\u015bciwo\u015bci rzutowa\u0144 podprzestrzeniowych&lt;\/title&gt;\n      &lt;title xml:lang=\"en\" titleType=\"TranslatedTitle\"&gt;Translation of Polish titles&lt;\/title&gt;\n    &lt;\/titles&gt;\n    &lt;publisher&gt;Springer&lt;\/publisher&gt;\n    &lt;publicationYear&gt;2010&lt;\/publicationYear&gt;\n    &lt;subjects&gt;\n      &lt;subject xml:lang=\"en\" subjectScheme=\"DDC\"&gt;830 German &amp;amp; related literatures&lt;\/subject&gt;\n      &lt;subject xml:lang=\"en\"&gt;Polish Literature&lt;\/subject&gt;\n    &lt;\/subjects&gt;\n    &lt;contributors&gt;\n      &lt;contributor contributorType=\"DataCollector\"&gt;\n        &lt;contributorName nameType=\"Personal\"&gt;Doe, John&lt;\/contributorName&gt;\n        &lt;givenName&gt;John&lt;\/givenName&gt;\n        &lt;familyName&gt;Doe&lt;\/familyName&gt;\n        &lt;nameIdentifier nameIdentifierScheme=\"ORCID\" schemeURI=\"http:\/\/orcid.org\/\"&gt;0000-0001-5393-1421&lt;\/nameIdentifier&gt;\n      &lt;\/contributor&gt;\n    &lt;\/contributors&gt;\n    &lt;language&gt;de&lt;\/language&gt;\n    &lt;resourceType resourceTypeGeneral=\"Text\"&gt;Monograph&lt;\/resourceType&gt;\n    &lt;alternateIdentifiers&gt;\n      &lt;alternateIdentifier alternateIdentifierType=\"ISBN\"&gt;937-0-4523-12357-6&lt;\/alternateIdentifier&gt;\n    &lt;\/alternateIdentifiers&gt;\n    &lt;relatedIdentifiers&gt;\n      &lt;relatedIdentifier relatedIdentifierType=\"DOI\" relationType=\"IsPartOf\"&gt;10.5272\/oldertestpub&lt;\/relatedIdentifier&gt;\n    &lt;\/relatedIdentifiers&gt;\n    &lt;sizes&gt;\n      &lt;size&gt;256 pages&lt;\/size&gt;\n    &lt;\/sizes&gt;\n    &lt;formats&gt;\n      &lt;format&gt;pdf&lt;\/format&gt;\n    &lt;\/formats&gt;\n    &lt;version&gt;2&lt;\/version&gt;\n    &lt;rightsList&gt;\n      &lt;rights rightsURI=\"http:\/\/creativecommons.org\/licenses\/by-nd\/2.0\/\"&gt;Creative Commons Attribution-NoDerivs 2.0 Generic&lt;\/rights&gt;\n    &lt;\/rightsList&gt;\n    &lt;descriptions&gt;\n      &lt;description xml:lang=\"la\" descriptionType=\"Abstract\"&gt;\n        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea\n        takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores\n        et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.\n      &lt;\/description&gt;\n    &lt;\/descriptions&gt;\n  &lt;\/resource&gt;<\/pre>\n<p>&nbsp;<\/p>\n<p>See also:<\/p>\n<p><a href=\"https:\/\/stackoverflow.com\/a\/49977184\/1485527\">https:\/\/stackoverflow.com\/a\/49977184\/1485527<\/a><\/p>\n<p>and<\/p>\n<p><a href=\"https:\/\/github.com\/jschnasse\/overflow\/tree\/master\/src\/test\/java\/stack24174963\">https:\/\/github.com\/jschnasse\/overflow\/tree\/master\/src\/test\/java\/stack24174963<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>You can use standard tools for it 1. Use the tool xjc from your jdk to generate Java classes from schema Since Java 9 you must explicitly add JAXB as module with \u2013add-modules java.se.ee See: How to resolve java.lang.NoClassDefFoundError: javax\/xml\/bind\/JAXBException in Java 9 Since Java 11 you have to download xjc in an extra step [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6,9],"tags":[],"class_list":["post-265","post","type-post","status-publish","format-standard","hentry","category-development","category-java"],"_links":{"self":[{"href":"https:\/\/jan.schnasse.org\/blog\/wp-json\/wp\/v2\/posts\/265","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jan.schnasse.org\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jan.schnasse.org\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jan.schnasse.org\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jan.schnasse.org\/blog\/wp-json\/wp\/v2\/comments?post=265"}],"version-history":[{"count":0,"href":"https:\/\/jan.schnasse.org\/blog\/wp-json\/wp\/v2\/posts\/265\/revisions"}],"wp:attachment":[{"href":"https:\/\/jan.schnasse.org\/blog\/wp-json\/wp\/v2\/media?parent=265"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jan.schnasse.org\/blog\/wp-json\/wp\/v2\/categories?post=265"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jan.schnasse.org\/blog\/wp-json\/wp\/v2\/tags?post=265"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}