0

Is there another way to track what is unmarshalled than write own reverter for each field?
I'm updating my local data based on json message and my problem is (simplified): I'm expecting json like

{ "items":  [ { "id":1, "name":"foobar",  "price":"12.34" }  ] }

which is then unmarshaled to class TItems by

UnMarshaller.TryCreateObject( TItems, TJsonObject( OneJsonElement ),  TargetItem  ) 

My problem is that I can't make difference between

{ "items":  [ { "id":1, "name":"",  "price":"12.34" }  ] }

and

{ "items":  [ { "id":1,  "price":"12.34" }  ] }

In both cases name is blank and i'd like to update only those fields that are passed on json message. Of course I could create a reverted for each field, but there are plenty of fields and messages so it's quite huge.

I tried to look REST.Jsonreflect.pas source, but couldn't make sense.

I'm using delphi 10.

MikaK
  • 1
  • 1
  • In JSON specification there is a difference between null value and empty string. What do you want precisely? – Erwin Jun 08 '16 at 09:37
  • Thanks for you reply. In this example case i wan't to know if name field actually exists in json. This is because client app sends only key field and modified field in json. And because Unmarshaller goes through classes fields not properties setters are never called. I'm wondering if I could somehow customize unmarshaller. I looked source code and noticed that there is JsonReflectAttribute attribute, but I couldn't make sense how to use it. – MikaK Jun 08 '16 at 10:04

2 Answers2

0

In Rest.Json unit there is a TJson class defined that offers several convenience methods like converting objects to JSON and vice versa. Specifically, it has a class function JsonToObject where you can specify options like for example ignore empty strings or ignore empty arrays. I think the TJson class can serve you. For unmarshalling complex business objects you have to write custom converters though.

Erwin
  • 1,896
  • 1
  • 11
  • 17
0

Actually, my problem was finally simple to solve. Instead of using TJSONUnMarshal.tryCreateObject I use now TJSONUnMarshal.CreateObject. First one has object parameters declared with out modifier, but CreateObject has Object parameter var modifier, so I was able to create object, initalize it from database and pass it to CreateObject which only modifies fields in json message.

MikaK
  • 1
  • 1