phpjson

php json_encode not present nullable properties


I have simple class with nullable string

class User {
   public string Name = "John";
   public ?string Email;
}

Then i searialize via json_encode it's return only one field

{
  "Name": "John"
}

but as say JSON-Schema, json can have null valuables, so i'm expecting

{
  "Name": "John",
  "Email": null
}

Is it possible (and how) to make right JSON with nullable properties in PHP?


Solution

  • Typed properties without explicit values are uninitialized, even properties of nullable types do not have a default null value (You can verify this with var_dump(new User)). Unless the class implements the JsonSerializable interface, uninitialized typed properties will be ignored by json_encode (as well as var_export and get_object_vars). Just give the Email property a value:

    class User {
       public string Name = "John";
       public ?string Email = null;
    }