ahausladen / JsonDataObjects

JSON parser for Delphi 2009 and newer
MIT License
413 stars 160 forks source link

casting null values to any datatype raise exception #14

Closed kattunga closed 8 years ago

kattunga commented 9 years ago

now if we try to cast a null value to any type of data an exception is raised:

var
  doc: TJsonObject;
  v: variant;
begin
  doc := TJsonObject.Create;
  try
    doc['nullvalue'] := null;

    // any of this raise an exception
    v := doc['nullvalue'].Value;
    v := doc['nullvalue'].IntValue;
    v := doc['nullvalue'].LongValue;
    v := doc['nullvalue'].FloatValue;
    v := doc['nullvalue'].DateTimeValue;
    v := doc['nullvalue'].BoolValue;

  finally
    doc.Free;
  end;
end;

Why don't we cast nulls like if it is jdtNone?

Also DataSet fields cast nulls to required datatypes:

  // if DataField.IsNull
  v := DataField.AsString;  // this return empty string
  v := DataField.AsInteger;  // this return 0
  ...

Also VarToString function:

  v := VarToString(null);   // this return empty string

I would like to implement this but I like to ask you first.

Regards Christian

ahausladen commented 8 years ago

Null means "JavaScript null". And that means that it is an object. And JsonDataObject doesn't allow to cast an object to a value type. Also a Variant Null can't be casted to a String, Integer, ... directly without throwing an exception.

ahausladen commented 8 years ago

You can now control this by setting "JsonSerializationConfig.NullConvertsToValueTypes" to "True". The default is "False".