Meme transcription: Panel 1. Two images of JSON, one is the empty object, one is an object in which the key name
maps to the value null
. Caption: “Corporate needs you to find the difference between this picture and this picture”
Panel 2. The Java backend dev answers, “They’re the same picture.”
Yeah, I’m also confused. If an attribute is null, I would prefer to simply not serialize it.
I’m sure there are edge cases where someone might prefer to include null attributes, but generally they should be treated the same either way.
Imagine you’re writing a CRUD API, which is pretty common.
If null attributes aren’t included in the payload, and someone does an update (typically a PATCH), how do you know which fields should be nulled out and which should be ignored?
I agree for many cases the two are semantically equivalent, but it’s common enough to not have them be equivalent that I’m surprised that it causes arguments
For an API there should always be a version parameter/endpoint, imho.
Edit for further context: Ideally, a parameter.
I wasn’t taking about new fields. I was talking about resource partial updates (eg PATCH, or commonly the U in CRUD).
If you just want to update a single field on a resource with 100 fields, rather than GETting the entire resource, updating the single field, and PUTting whole thing back, just do a PATCH with the single field.
Likewise if you’re POSTing a resource that has nullable fields, but the default value isn’t null, how do you indicate that you want the default value for a given field? Do you have to first query some metadata API? That doesn’t seem ideal, when this existing pattern exists
Those are two very fair points - I agree.
That’s interesting. I’m on the opposite team. If a customer model defines an optional birthday, for instance, I’d rather have it serialized as a null value if it’s not available for a specific customer.
The biggest reason for me is that it’s less data to send over a network. Especially when I’m working with lists of objects, including null fields can add a noticeable chunk to the payload.
There are some cases where it might be worth it to differentiate “No value” and “No attribute”, but in most cases they can be treated the same, since the data should really be validated against a schema anyway.
Depends on the application. When the user is able to set the schema via database, then you cannot assume the shape of the data.
I’m not sure I understand what you mean.
Yeah, nevermind, I didn’t know what I wrote either. I need my sleep lol.