F # type deserialization using json.net and a json property containing the @ character

I have an F # type that I am deserializing for an object from the contents of an HTTP web request. The API I'm calling uses the odata protocol, and the contents of this request are in the following format containing the @odata.context key.

 { "@odata.context":"OData", "Value":"token" } 

I use Json.net to deserialize the content back to my type F #, type F # looks like this

 type Success = { [<JsonProperty(PropertyName = "@odata.context")>] ``odata.context``: string; Value: string; } 

odata.context always null in this situation.

I tried both of the following (with the @ symbol in a property name of type F #) and the result is NULL

 let test1 = JsonConvert.DeserializeObject<Success>("{\"@odata.context\": \"odata.context\", \"Value\": \"token\"}")) 

(without the @ symbol in the name of a property of type F #). It deserializes correctly.

 let test2 = JsonConvert.DeserializeObject<Success>("{\"odata.context\": \"odata.context\", \"Value\": \"token\"}")) 

I believe this may be due to the @ symbol in the property name.

Any ideas for a solution would be great.

+5
source share
1 answer

If you do not have the option to upgrade Json.Net to a newer one (for example, 8.0.2), you can use Newtonsoft.Json.Linq .

Example:

 open System open Newtonsoft.Json.Linq type Success = { ``odata.context``: string; Value: string; } let json = "{\"@odata.context\":\"OData\",\"Value\":\"token\"}" let p = JObject.Parse(json) {``odata.context`` = p.["@odata.context"] |> string ;Value = p.["Value"] |> string} |> printfn "%A" 

Print

 {odata.context = "OData"; Value = "token";} 

Link

https://dotnetfiddle.net/SR16Ci

+2
source

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


All Articles