apache-camelapache-drillhl7-v2

Converting HL7 v2 to JSON


I am looking to convert HL7 v2 (older EDI format) messages to JSON, so I could make them processable under Apache Drill and compressible under Parquet.

I looked into HAPI, but I am not having luck finding utility for non-XML HL7 to JSON conversion.

Does anyone have a suggestion or a reference to a library?


Solution

  • Just use HAPI to convert to XML. The code below requires Saxon, because the XML-to-JSON requires XSLT 2.0, but if you already have a method to convert XML to JSON, then you just need the first two lines, which are entirely HAPI. You should download the XSLT locally for production, of course. :-)

    String convertHL7ToJson(Message message) {
        try {
            DefaultXMLParser xmlParser = new DefaultXMLParser(new CanonicalModelClassFactory("2.6"));
            String xml = xmlParser.encode(message);
            Transformer xmlTransformer = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", null).newTransformer(
                new StreamSource(new StringReader(readFileFromURL("https://github.com/bramstein/xsltjson/raw/master/conf/xml-to-json.xsl")))
                );
              StringWriter result = new StringWriter();
              xmlTransformer.transform(
                 new StreamSource(new StringReader(xml)), new StreamResult(result)
              );
              return result.toString();
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return null;
    }
    
    String readFileFromURL(String url) {
        InputStream is = null;
        try {
            return new Scanner(is = new URL(url).openStream(), "UTF-8").useDelimiter("\\A").next();
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            if(is != null)
                try {
                    is.close();
                } catch (Throwable ignored){}
        }
        return null;
    }
    

    This creates output like this:

    "ORM_O01":{"MSH":{"MSH.1":"|","MSH.2":"^~\\&","MSH.3":{"HD.1":"TEST"},"MSH.4":{"HD.1":"TEST000","HD.2":"BL"},...