FSharp.Json: JSON Serialization Library
FSharp.Json is F# JSON serialization library based on Reflection it's written in F# for F#.
Basic Usage Example
Here's basic example of FSharp.Json usage:
#r "FSharp.Json.dll"
open FSharp.Json
// Your record type
type RecordType = {
stringMember: string
intMember: int
}
let data: RecordType = { stringMember = "The string"; intMember = 123 }
// serialize record into JSON
let json = Json.serialize data
printfn "%s" json
// json is """{ "stringMember": "The string", "intMember": 123 }"""
// deserialize from JSON to record
let deserialized = Json.deserialize<RecordType> json
printfn "%A" deserialized
// deserialized is {stringMember = "some value"; intMember = 123;}
Table of Contents
Why?
Why we need yet another F# JSON serialization library?
Well, if you happy with the library that you are using currently then probably you do not need another one.
There are several available options to choose from:
While all of these libraries do provide some good functionality all of them seem to have a weakness.
Some of them are written in C# without out of the box support for F# types.
Additionally null safety is alien concept in C# however it is a must in F#.
Other libraries provide only low-level functionality leaving a lot of cumbersome coding work to library user.
The type provider library forces developer to define JSON schema in form of json examples which is far from convenient way of defining schemas.
FSharp.Json was developed with these values in mind:
- Easy to use API
- Automatic mapping of F# types into JSON
- Out of the box support for F# types
- Null safety
How?
FSharp.Json is pure F# library.
It uses Reflection to get information about F# types at runtime.
The code from FSharp.Data library is used for parsing JSON.
The JsonValue type is internalized in the FSharp.Json library.
The core of FSharp.Json library is located in single Core.fs file.
Documentation
This document describe all details of FSharp.Json library. The source code also has thorough documentation in comments to main types. Each feature of FSharp.Json is thoroughly covered by unit tests.
API Overview
Most of API functions are defined in Json module.
Easiest way to serialize is to call Json.serialize function.
It serializes any supported F# type to string containing JSON.
Similarly easiest way to deserialize is to call Json.deserialize<'T> function.
It takes string containing JSON and returns instance of type 'T.
Advanced functions
Functions Json.serialize and Json.deserialize are using default configuration.
Whenever custom configuration should be used following functions are useful:
Json.serializeEx
Json.deserializeEx<'T>
Prefix Ex stands for "extended". Both of these functions take JsonConfig instance as a first parameter.
Configuration
JsonConfig represents global configuration of serialization.
There's convenient way to override default configuration by using JsonConfig.create function.
All parameters of the function are optional and those that are provided override default values.
For example, custom jsonFieldNaming could be found here.
Unformatted JSON
Some products like Apache Spark require unformatted JSON in a single line.
It is usefull to produce unformatted single line JSON in some other scenarios.
There is a function to produce unformatted JSON: Json.serializeU.
U stands for "unformatted". It has the same signature as Json.serialize function.
The function is a shorthand to using unformatted member on JsonConfig.
Supported Types
Here's full list of F# types that are supported by FSharp.Json library.
| F# Type |
JSON Type |
sbyte byte int16 uint16 int uint int64 uint64 bigint single float decimal |
number |
| string |
string |
| char |
string |
| bool |
bool |
| DateTime |
string according to ISO 8601 number epoch time using transform |
| DateTimeOffset |
string according to ISO 8601 number epoch time using transform |
| TimeSpan |
string, example "23:00:10" |
| Guid |
string |
| Uri |
string using transform |
| Enum |
string enum value name number enum value read Enums section |
| option |
option is not represented by itself
None value might be represented as null or omitted read more in Null Safety section |
| tuple |
list |
| record |
object |
| map |
object |
array list |
list |
| union |
object with special structure read more in Unions section |
| obj |
read Untyped Data section |
Customizing JSON Fields Names
When record type instance is serialized into JSON members names are used as JSON fields names.
In some scenarios the JSON should have different fields names then F# record type.
This section describes how FSharp.Json library provides JSON customization abilities.
Change JSON field name
JSON field name could be easily customized with JsonField attribute:
#r "FSharp.Json.dll"
open FSharp.Json
// attribute stringMember with JsonField
type RecordType = {
[<JsonField("different_name")>]
stringMember: string
intMember: int
}
let data: RecordType = { stringMember = "The string"; intMember = 123 }
let json = Json.serialize data
printfn "%s" json
// json is """{ "different_name": "The string", "intMember": 123 }"""
// pay attention that "different_name" was used as JSON field name
let deserialized = Json.deserialize<RecordType> json
printfn "%A" deserialized
// deserialized is {stringMember = "some value"; intMember = 123;}
In example above JsonField attribute affects both serialization and deserialization.
Change all fields names
What if all fields names should be different in JSON compared to F# member names?
This could be needed for example if naming convention used in F# does not match JSON naming convention.
FSharp.Json allows to map fields names with naming function.
In the example below all camel case F# record members are mapped into snake case JSON fields:
#r "FSharp.Json.dll"
open FSharp.Json
// attribute stringMember with JsonField
type RecordType = {
stringMember: string
intMember: int
}
let data: RecordType = { stringMember = "The string"; intMember = 123 }
// create config with JSON field naming setting
let config = JsonConfig.create(jsonFieldNaming = Json.snakeCase)
let json = Json.serializeEx config data
printfn "%s" json
// json is """{ "string_member": "The string", "int_member": 123 }"""
// pay attention that "string_member" and "int_member" are in snake case
let deserialized = Json.deserializeEx<RecordType> config json
printfn "%A" deserialized
// deserialized is {stringMember = "some value"; intMember = 123;}
The Json module defines two naming functions that could be used out of the box: snakeCase and lowerCamelCase.
The one can define it's own naming rule - it's just a function string -> string.
Null Safety
FSharp.Json is null safe.
This means that library will never deserialize JSON into anything with null value.
FSharp.Json treats option types as an instruction that value could be null in JSON.
For example member of type string can't get null value in FSharp.Json, however string option member can have None value which is translated into null in JSON.
Same logic applies to all types supported by FSharp.Json library.
See examples in sections below.
Deserialization of null
In the example below stringMember member can't be assigned to null even though F# allows string to be null:
#r "FSharp.Json.dll"
open FSharp.Json
type RecordType = {
stringMember: string
}
let json = """{"stringMember":null}"""
// this attempt to deserialize will throw exception
let deserialized = Json.deserialize<RecordType> json
What if the member stringMember could be null in JSON?
In such case the record type should explictly use string option type:
#r "FSharp.Json.dll"
open FSharp.Json
type RecordType = {
stringMember: string option
}
let json = """{"stringMember":null}"""
// this attempt to deserialize will work fine
let deserialized = Json.deserialize<RecordType> json
// deserialized.stringMember equals to None
printfn "%A" deserialized
If value could be null or missing in JSON then F# type used for corresponding member should be option.
Customization of null deserialization
What is the difference between missing field in JSON and field assigned to null?
By default FSharp.Json library treats both cases as None, however you can customize this logic.
Behaviour that is used to treat option types could be configured: