none
F# how to serialize records to nested JSon data RRS feed

  • Question

  • If I have some records in F#:

    type Coureur=
        { runner_name: string
          distance : string
          unit : string
          score: float }
    
    let stoppage = 
        seq [
            {  runner_name= "No 1" ; distance = "100M"; unit = "seconds"; score = 10.0}
            {  runner_name= "No 2" ; distance = "200M"; unit = "seconds"; score = 20.0}
        ]

    I want to serialize the records to the nested Json data, like the following:

    {

      "sports": {

        "measure-type": "Metric",

        "runner-type": "track-field",

        "runners": [

        {

        "runner-name":"No 1" , "distance": "100M", "unit": "seconds", "score": 10.0

        },{

        "runner-name":"No 2" , "distance": "200M", "unit": "seconds", "score": 20.0

        }]

    }

    The top part of the JSon data is fixed, only the nested part of “runners” are from the records in the above code.

    I can’t find good example to do this, which one I should use?

    DataContract or JSon type provider?

    Please advise.

    Thanks,


    Saturday, April 21, 2018 11:03 PM

All replies

  • hello,

    If I understand, you want to have a record type with nested sequence of runners, and serialize it to Json, while keeping the same values for the Coureur record, If So, here is a little code snippet: 

    type Coureur=
        { runner_name: string
          distance : string
          unit : string
          runners: Coureur seq
          score: float }
    
    let coureur =
        { runner_name="coureur1"
          distance="100M"
          unit="Seconds"
          score=10.0
          runners = [] }
    
    let runner_mois9 = 
        seq [
            {  runner_name= "No 1" ; distance = "100M"; unit = "seconds"; score = 10.0; runners = [] }
            {  runner_name= "No 2" ; distance = "200M"; unit = "seconds"; score = 20.0; runners = [] }
        ]
    
    let runner_mois10 = 
        seq [
            {  runner_name= "No 1" ; distance = "100M"; unit = "seconds"; score = 10.0; runners = []}
            {  runner_name= "No 2" ; distance = "200M"; unit = "seconds"; score = 20.0; runners = []}
        ]
    
    let coureur_mois9 = 
        { coureur with runners = runner_mois9 }
    
    
    let coureur_mois10 = 
        { coureur with runners = runner_mois10 }
    
    let serialize o = 
        JsonConvert.SerializeObject o
    
    coureur_mois9 
    |> serialize 
    |> printfn "%s"
    
    printfn "%s" (JsonConvert.SerializeObject coureur_mois10)
    

    Hope it help;

    Monday, September 3, 2018 7:19 PM