When I deserialize some JSON into this F# class, the property setter for the CountResults
property is not working as expected.
I have this class:
type CounterResponse () =
let mutable countsList:List<CountResult> = List<CountResult>()
let mutable countResultsLookup:IReadOnlyDictionary<string,int> = readOnlyDict [("", 0)]
member this.CountResults
with get() = countsList
and set(value:List<CountResult>) =
countResultsLookup <- value |> Seq.map(fun c -> c.Name, c.Count) |> readOnlyDict
countsList <- value
...
If I create an instance of this class with F# using:
let countResults = seq {
{Name = "Count01"; Count = count}
{Name = "Count02"; Count = count}
{Name = "Count03"; Count = count}
}
let response = CountersResponse(CountResults = List<CountResult>(countResults))
Then the CountResults
property setter runs and sets the values of the private backing fields countsList
and countResultsLookup
.
However, when I create an instance of this class with NewtonSoft.Json only the countsList
backing field is set and I can't get the breakpoint in the setter code to stop. It appears that NewtonSoft is bypassing my property setter code, finding the countsList
backing field, and setting it directly.
let response = JsonConvert.DeserializeObject<CounterResponse>(
"""
{
"countResults": [
{ "name": "Count01","count": 4 },
{ "name": "Count02", "count": 2 },
{ "name": "Count3", "count": 1 },
],
"version": "6.0.0.0",
"errorSection": {
"validationErrors": [],
"code": "200",
"message": "Success"
}
}
"""
)
In the above example the backing field countResultsLookup
is set to the default value readOnlyDict [("", 0)]
and countList
contains the 3 counts in the JSON.
Is there an option to tell NewtonSoft to use the property setter so that I can get the expected results in both cases?