Question

I trying to execute sample from official web blog of Json.NET

http://james.newtonking.com/archive/2014/02/01/json-net-6-0-release-1-%E2%80%93-jsonpath-and-f-support

I created F# console application with latest Json.NET (Json.NET 6.0.2)

I pasted code sample and adopted it to F# 3.0:

type Shape =
    | Rectangle of float * float
    | Circle of float
    | Empty 

[<EntryPoint>]
let main argv =  

let shape1 = Rectangle(1.3, 10.0)
let json = JsonConvert.SerializeObject(shape1)
// {
//   "Case": "Rectangle",
//   "Fields": [
//     1.3,
//     10.0
//   ]
// }


let shape2 = JsonConvert.DeserializeObject<Shape>(json)

Console.ReadKey() |> ignore
0

But it doesn't work. Basically JsonConvert.SerializeObject(shape1) returns "{}".

I am curious why it doesn't work?

Beside of that, I use Json.NET in F# WebAPI and it works.

I have uploaded the whole project on github: https://github.com/AntyaDev/SerializationTest

Was it helpful?

Solution

Like Patryk Ćwiek, I can't reproduce the behaviour you describe. It works fine with Json.NET 6.0.2 on F# 3.1. However, there are some problems with your code listing, which doesn't compile as given.

You need to open the appropriate namespaces (or modules):

open System
open Newtonsoft.Json

Also, F# uses significant whitespace, so the code listing should be like on the original blog:

type Shape =
    | Rectangle of width : float * length : float
    | Circle of radius : float
    | Empty 

[<EntryPoint>]
let main argv =  

    let shape1 = Rectangle(1.3, 10.0)
    let json = JsonConvert.SerializeObject(shape1)
    // {
    //   "Case": "Rectangle",
    //   "Fields": [
    //     1.3,
    //     10.0
    //   ]
    // }


    let shape2 = JsonConvert.DeserializeObject<Shape>(json)

    Console.ReadKey() |> ignore
    0

Notice that all code below let main argv = is indented.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top