Newtonsoft.Json serializes multiple items twice

I noticed some strange conclusion from Newtonsoft.Json today, I'm not sure if this is an interaction with F # types or something that could happen in C #, so I tagged. I have a list of the following entry:

type SplitTracker = { [<JsonIgnore>] split : SplitDefinition mutable start : duration mutable ``end`` : duration mutable lapCount : int mutable duration : duration Option } 

I serialize it using JsonConvert.SerializeObject and I get the following odd output:

  "splits": [ { " start@ ": "0.00", " end@ ": "0.00", " lapCount@ ": 0, " duration@ ": null, "start": "0.00", "end": "0.00", "lapCount": 0, "duration": null }, { " start@ ": "0.00", " end@ ": "0.00", " lapCount@ ": 0, " duration@ ": null, "start": "0.00", "end": "0.00", "lapCount": 0, "duration": null } 

Does anyone know why this might happen? The data is correct, the problem of duplication of fields with the symbol "@".

+5
source share
1 answer

How you determined your entry is the culprit here. Record fields are displayed as properties, but you are using mutable properties. F # will turn this into a class that has fields for each of your mutables (name is the name of the property, the @ prefix) and properties that read them.

Now Json will try to serialize all fields and all properties - hence, you will get duplication.

Try it in F # interactive:

 type SplitTracker = { mutable start : float } let t = typeof<SplitTracker> let fields1 = t.GetFields() // This will give you a field '@start' let props1 = t.GetProperties() // This will give you a property 'start' 

Compare this to what you get when using simple recording:

 type SplitTracker2 = { start : float } let t2 = typeof<SplitTracker2> let fields2 = t2.GetFields() // You will not see any fields let props2 = t2.GetProperties() // There is a single property 'start' 

This must be properly serialized. In addition, it makes your code more idiomatic.

+6
source

Source: https://habr.com/ru/post/1246077/


All Articles