0

I want to convert a xml to json using jackson library. Initially, I generated java classes based on the xsd file using jaxb. I wonder how to differentiate between a default null and the null value in the xml.

  <n2:test>
    <address/>
  </n2:test>

  class Test {
    String address; >> give null value
    String IC; >> give null value (default is null)
  }
Jack
  • 89
  • 6
  • I wonder *why* differentiate between them? A `null` is a `null`. If you're writing logic based on whether it's an explicit or an implicit null, you might want to rethink your idea. – Kayaman Feb 15 '22 at 12:55
  • @Kayaman It is no about explicit or implicit null. if the application receive a XML which contain valid values for address and IC, then the application then convert the XML to json (address = ABC and IC = 123A) and multicast to other application. If the application receive a XML which only has address field ( the value is null), the application has to convert the XML to JSON (address = null) and multicast to other applications. Thus, I want to avoid XML to JSON (address = null and IC = null) – Jack Feb 15 '22 at 13:19
  • You're not representing [null in XML](https://stackoverflow.com/q/774192/2541560) properly. Secondly, if you only want to send non-null values, the Jackson serializer has an option for that. However if you're trying to do some kind of "only send explicit nulls", then it's back to my original comment: there is only one kind of null, and you should rethink your approach. – Kayaman Feb 15 '22 at 13:44
  • it is my mistake. for null representation in the XML. it should be
    . I using JAXB to unmarshall the XML to Java Object. Then, I think both value of the address and IC will be null in the Test Java Object Class. Then, if I convert the Java Object to JSON and the result of the JSON will be { address : null, student : null}. However, I only want {address : null}. Is it possible ? Thank you for your help
    – Jack Feb 15 '22 at 13:53
  • Well, you can't have that. You have two nulls and there's nothing different between them. You can have Jackson omit both of them, or serialize both of them, but they will not be treated any differently. – Kayaman Feb 15 '22 at 13:53
  • Yeah. both are null value. But I need to distinguish whether or not the value was present and the value was set explicitly to null in XML – Jack Feb 15 '22 at 14:20
  • I'll tell you when you tell me which of these two numbers: `2` and `2` is a regular two and which one is the result of `1+1`. – Kayaman Feb 15 '22 at 14:27
  • I understand it is no. No worry. The only way I guess should change the code to use Java.Optional or JAXBElement. – Jack Feb 15 '22 at 19:59

0 Answers0