Jeremy
Jeremy

Reputation: 46350

Convert fhir between XML and Json

Is there a way to convert a fhir bundle from json to xml by means that is independent of the FHIR version used?

I think the .net fhir api by firely can do it, but any given version of the api seems to be specific to a certain release of FHIR.

Upvotes: 0

Views: 2415

Answers (2)

Abel
Abel

Reputation: 41

The problem is that a FHIR Bundle (or any resource) implicitly always has a version. The rationale is that each FHIR version has (or can have) a different underlying data model. It is possible though, using the .NET FHIR API (specifically package https://www.nuget.org/packages/Hl7.Fhir.Serialization) to do the conversion with minimal version differences. The following code does the conversion using the version-independent ISourceNode (http://docs.simplifier.net/fhirnetapi/parsing/isourcenode.html)

using Hl7.Fhir.ElementModel;
using Hl7.Fhir.Serialization;    

var xml = "<Patient xmlns=\"http://hl7.org/fhir\"><identifier><use value=\"official\" /></identifier></Patient>";
var patientNode = FhirXmlNode.Parse(xml);
var typedElement = patientNode.ToTypedElement();
var json = typedElement.ToJson();

The above code has one problem though, as VS will tell you. Using ToTypedElement() without parameters is dangerous because ignoring the version is. It will work in many cases though and if it is good enough for you that may be the way to go.

A safer solution is to use the same code, but to additionally use a so-called IStructureDefinitionSummaryProvider (apologies for the naming ;) to provide the API with specific version information. Implementations for this interface can be found in version-specific API libraries, e.g. https://www.nuget.org/packages/Hl7.Fhir.R4.

using Hl7.Fhir.ElementModel;
using Hl7.Fhir.Serialization;
using Hl7.Fhir.Specification;

var xml = "<Patient xmlns=\"http://hl7.org/fhir\"><identifier><use value=\"official\" /></identifier></Patient>";
var patientNode = FhirXmlNode.Parse(xml);
var summaryProvider = new PocoStructureDefinitionSummaryProvider();
var typedElement = patientNode.ToTypedElement(summaryProvider);
var json = typedElement.ToJson();

You may be able to inject these PocoStructureDefinitionSummaryProviders based on some property of the input you are reading from. That is how we do it in the Vonk FHIR server for instance.

Upvotes: 4

Grahame Grieve
Grahame Grieve

Reputation: 3586

The FHIR java validator can do this for any version. That might be suitable depending on what you need to use it

Upvotes: 2

Related Questions