rpgmaker / NetJSON

Faster than Any Binary? Benchmark: http://theburningmonk.com/2014/08/json-serializers-benchmarks-updated-2/
MIT License
231 stars 29 forks source link

Can NetJSON serialize nullable int? #221

Closed juniormayhe closed 5 years ago

juniormayhe commented 5 years ago

I am trying to understand nullable serialization with NetJSON. My code:

string s = NetJSON.Serialize(myObject, 
  new NetJSONSettings { 
      UseEnumString = false, 
      SkipDefaultValue = false, 
      DateFormat = NetJSONDateFormat.JsonNetISO });

myObject is a class with

public int? Id {get; set;}

serialized string outputs

"id": 0

instead of

"id": null

is this expected @rpgmaker ?

rpgmaker commented 5 years ago

Can you add skip default to the settings of your class? Thanks

juniormayhe commented 5 years ago

It seems SkipDefaultValue = true is removing nullable fields from serialized string.

I was hoping that NetJSON generate the same output as Newtonsoft. This is a scenario where we already have serialized strings persisted in database (created by newtonsoft) and want to migrate solution to NetJSON.

The idea is to keep the same data format to have backward compatibilty between different serialization frameworks and avoid any issues that might happen with deserialization. If migration is possible we would like to have a go.

Here is the expected behavior

Datatype Newtonsoft serialized string NetJSON current serialized string NetJSON expected serialized string
int id=0 "id": 0 none, suppressed (by SkipDefaultValue=true) "id": 0
int? id=null "id": null none, suppressed (by SkipDefaultValue=true) "id": null
rpgmaker commented 5 years ago

Since your data is already string. By using skip default = true. it will give you the expected value when deserialized that would match the object graph that newtonsoft creates. The generated string been sent should not matter much because no matter what serializer you use at the end of the day. It will output matching result.

If you Jil, and it does not find "id=null" in your payload, it will not set the nullable. The absence of a field means no setting of the property. Unless you are saying that the constructor of your object already set some default values in which you want to override. Making the skipDefault to false and returning null for primitive type is not difficult to do since all i have to do is check is hasValue

int id = 0; image

int? id = null; image

rpgmaker commented 5 years ago

Let me know your thought. Thanks

rpgmaker commented 5 years ago

This is the behavior i get if i change it based on what you said.

int? id = null image

rpgmaker commented 5 years ago

int? id = 0 give the following with skipDefault = false

image

rpgmaker commented 5 years ago

Please verify if the changes i did solves your problem by using the code from the branch. If so, i can create a nuget package for it.

Thanks,