LinuxForHealth / FHIR

The LinuxForHealth FHIR® Server and related projects
https://linuxforhealth.github.io/FHIR
Apache License 2.0
330 stars 157 forks source link

Unable to create Bundle class object from JsonObject in Kotlin #3760

Open anshul90 opened 2 years ago

anshul90 commented 2 years ago

Describe the bug I'm trying to create Bundle object from jsonObject but it throws InvalidDefinitionException with error message Cannot construct instance of com.ibm.fhir.model.resource.Bundle (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

Environment I'm using it for android in gradle file implementation 'com.ibm.fhir:fhir-model:4.10.2'

To Reproduce Steps to reproduce the behavior: Call:

val m = ObjectMapper() val myClass: Bundle = m.readValue(credentialSubject.getAsJsonObject("fhirBundle").toString(), Bundle::class.java)

Expected behavior It should create as a Bundle Object

punktilious commented 2 years ago

To deserialize any com.ibm.fhir.model resource you need to use FHIRParser:

        try (InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(bundlePath)) {
            final Bundle bundle = (Bundle) FHIRParser.parser(Format.JSON).parse(is);
            ...
        }

The parser performs a lot of checking on the resource to ensure it conforms to the spec. If you need to perform further validation of the resource, you should consider using FHIRValidator on the resource value returned by the parser.

punktilious commented 2 years ago

You might also want to take a look at our FHIRClientImpl which uses jax-rs configured with custom components to handle the serialization/deserialization of FHIR resources. This is used extensively in the fhir-server-test project. See also FHIRJsonProvider which implements both MessageBodyReader and MessageBodyWriter

punktilious commented 2 years ago

@anshul90 please let us know if the above info is helpful.

anshul90 commented 2 years ago

Hi, I tried as you said but still I'm unable to get the result what I need. I'm using VerifiableCredential library also since years which works fine for me.

I'm using it with Kotlin. And You can find the snippet below.

fun Credential.fhirBundleEntry(): JsonArray? {
    return if (credentialSubject?.has("fhirBundle") == true) {
        val iss: InputStream? = ClassLoader.getSystemClassLoader().getResourceAsStream(credentialSubject.getAsJsonObject("fhirBundle").toString())
        val bundle = FHIRParser.parser(Format.JSON).parse(iss) as Bundle

        credentialSubject.getAsJsonObject("fhirBundle").getAsJsonArray("entry")
    } else null
}

In above snippet, Bundle always gets null.