Skip to content

Case insensitive attribute fieldnames #16

@Spelt

Description

@Spelt

Hi

I like this lib. Its a nice simple one.

I do have an impprovement (I think). Take look at this example:

When there is a Json string with a field called 'MainBackgroundColor' it will not deserialize if I have this record (or class):

  [DJSerializable]
  TMemberAppStyleDefinition = record
  public
     [DJValue('MainbackgroundColor')]
     MainbackgroundColor: string;
  end;

Notice the MainbackgroundColor should be MainBackgroundColor

It needs to be precise and that is because how the Delphi JSON works. The DJValue needs to be exact the same. This can be a problem because these are easy mistakes to make. I propose a simple solution to make your lib less error phrone for the user.

 // check if the field name is valid
    if string.IsNullOrWhiteSpace(jsonFieldName) then
    begin
      raise EDJError.Create
        ('Invalid JSON field name: is null or whitespace. ', context);
    end;

    // Check on case sensitive mistakes with the fieldname and correct for this.
    for var i := 0 to jsonObject.Count - 1 do
    begin
      var candidate := jsonObject.Pairs[i];
      if SameText(candidate.JsonString.Value, jsonFieldName) then
      begin
        if candidate.JsonString.Value <> jsonFieldName then
          jsonFieldName := candidate.JsonString.Value;
      end;
    end;

    // check if the field name exists in the json structure
    JsonValue := jsonObject.GetValue(jsonFieldName);
    if required then
    begin
      // the field is required but was not found
      if JsonValue = nil then
      begin
        raise EDJRequiredError.Create('Value with name "' + jsonFieldName +
          '" missing in JSON data. ', context);
      end;
    end
    else .....
........
........

Its just a suggestion.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions