Search code examples
jsonparsingjsonparsersubdocument

Json - optional subdocument


I´m getting a json from an application with a couple of nested subdocuments. Some of those documents are optional and not present all the time. I´m wondering if there is a best practice how to handel this.

e.g. (The document is just an example, the real one looks differnt but I can´t post it, the Example is copied from: How to represent sub-documents in JSON array as Java Collection using Jackson?): The Adreess subdocument is not present in every document I receive.

 {
  "attributes": {
    "type": "Lead",
    "url": "/services/data/v30.0/sobjects/Lead/00Qi000000Jr44XEAR"
  },
  "Id": "00Qi000000Jr44XEAR",
  "Name": "Kristen Akin",
  "Address": {
      "city": null,
      "country": "USA",
      "state": "CA",
      "stateCode": null,
      "street": null
  },
  "Phone": "(434) 369-3100"
}

Currently I´m receiving the data in the worst possible way I can imagine with a differnt type, which is like:

{
  "attributes": {
    "type": "Lead",
    "url": "/services/data/v30.0/sobjects/Lead/00Qi000000Jr44XEAR"
  },
  "Id": "00Qi000000Jr44XEAR",
  "Name": "Kristen Akin",
  "Address": "",
  "Phone": "(434) 369-3100"
}

I want to suggest better ways and I´m wondering whats the best one?

  1. Leaving the adress subdocument out completely
  2. receiving "Adress: null"
  3. receiving Adress: {}
  4. receiving Adress: {"city": null, "country": null, ...}
  5. anything else

Personally I would go with Nr. 3 because I still get a (sub)document and can treat it the usual way. Does anythin speak against it or are there any best practices for this situation?

Thanks in advance.

Best regards.


Solution

  • Go with 3.

    1. Leaving the adress subdocument out completely

    Would work for many deserialization tools, but it is hard to identify the structure and identify if something is missing on debugging easily

    1. receiving "Adress: null"

    Would work for many deserialization tools, but it is not a good practice to deliver null for more complex attributes like arrays or objects. You cannot identify, that this is a complex object easily.

    1. receiving Adress: {}

    It is a good practice to deliver empty arrays if they are empty and empty objects, if they are empty. You can identify that there could be a complex object but it is not available here. Please go with this solution

    1. receiving Adress: {"city": null, "country": null, ...}

    Don't do this. It gives you more details for the complex object, but you cannot identify easily if the address was not added on purpose or if the API partner sends incomplete address data by accident or if incomplete data is valid on their side.