Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 841771
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T05:51:13+00:00 2026-05-15T05:51:13+00:00

Basically I want to have a single construct to deal with serializing to both

  • 0

Basically I want to have a single construct to deal with serializing to both JSON and formatted xml. Records worked nicely for serializing to/from json. However XmlSerializer requires a parameterless construtor. I don’t really want to have to go through the exercise of building class objects for these constructs (principle only). I was hoping there could be some shortcut for getting a parameterless constructor onto a record (perhaps with a wioth statement or something). I can’t get it to behave – has anybody in the community had any luck?

module JSONExample
    open System
    open System.IO 
    open System.Net 
    open System.Text 
    open System.Web 
    open System.Xml
    open System.Security.Authentication 
    open System.Runtime.Serialization //add assemnbly reference System.Runtime.Serialization System.Xml
    open System.Xml.Serialization
    open System.Collections.Generic 

    [<DataContract>]            
    type ChemicalElementRecord = { 
        [<XmlAttribute("name")>]
        [<field: DataMember(Name="name") >] 
        Name:string 

        [<XmlAttribute("name")>]
        [<field: DataMember(Name="boiling_point") >] 
        BoilingPoint:string 

        [<XmlAttribute("atomic-mass")>]
        [<field: DataMember(Name="atomic_mass") >] 
        AtomicMass:string 
    } 

    [<XmlRoot("freebase")>]
    [<DataContract>] 
    type FreebaseResultRecord = { 
        [<XmlAttribute("code")>]
        [<field: DataMember(Name="code") >] 
        Code:string 

        [<XmlArrayAttribute("results")>]
        [<XmlArrayItem(typeof<ChemicalElementRecord>, ElementName = "chemical-element")>]
        [<field: DataMember(Name="result") >] 
        Result: ChemicalElementRecord array

        [<XmlElement("message")>] 
        [<field: DataMember(Name="message") >] 
        Message:string 
        } 


    let getJsonFromWeb() = 
        let query = "[{'type':'/chemistry/chemical_element','name':null,'boiling_point':null,'atomic_mass':null}]"
        let query = query.Replace("'","\"") 
        let queryUrl = sprintf "http://api.freebase.com/api/service/mqlread?query=%s" "{\"query\":"+query+"}" 

        let request : HttpWebRequest = downcast WebRequest.Create(queryUrl) 
        request.Method <- "GET" 
        request.ContentType <- "application/x-www-form-urlencoded" 

        let response = request.GetResponse() 

        let result = 
            try 
                use reader = new StreamReader(response.GetResponseStream()) 
                reader.ReadToEnd(); 
            finally 
                response.Close() 

        let data = Encoding.Unicode.GetBytes(result); 
        let stream = new MemoryStream() 
        stream.Write(data, 0, data.Length); 
        stream.Position <- 0L 
        stream



    let test =
        // get some JSON from the web
        let stream = getJsonFromWeb()

        // convert the stream of JSON into an F# Record
        let JsonSerializer = Json.DataContractJsonSerializer(typeof<FreebaseResultRecord>) 
        let result: FreebaseResultRecord = downcast JsonSerializer.ReadObject(stream) 

        // save the Records to disk as JSON 
        use fs = new FileStream(@"C:\temp\freebase.json", FileMode.Create) 
        JsonSerializer.WriteObject(fs,result)
        fs.Close()

        // save the Records to disk as System Controlled XML
        let xmlSerializer = DataContractSerializer(typeof<FreebaseResultRecord>);
        use fs = new FileStream(@"C:\temp\freebase.xml", FileMode.Create) 
        xmlSerializer.WriteObject(fs,result)
        fs.Close()

        use fs = new FileStream(@"C:\temp\freebase-pretty.xml", FileMode.Create) 
        let xmlSerializer = XmlSerializer(typeof<FreebaseResultRecord>)
        xmlSerializer.Serialize(fs,result)
        fs.Close()

ignore(test)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T05:51:14+00:00Added an answer on May 15, 2026 at 5:51 am

    Looks like you can’t change a record to a class – or add a edfault constructor to it.

    The example provided (basedof off this article: Link) gets a stream of json from api.freebase.com; we then deserialize into the attributed classes; next serialize it as Json to disk; then serialize it as Xml to disk (using DataContract); finally, with the best controll of the output serialize it as Xml to disk (using XmlSerializer):

    Notes:

    DataContract(family of) attributes for
    DataContractJsonSerializer and
    JSON.DataContractJsonSerializer –
    these occur over the class names and
    the memeber variables. DataContract
    stuff was straight forward – and
    works on record types as well.

    XmlSerializer(family of) attributes
    over the class and the Property
    Getter/Setter. This requires the type
    is an object with a default
    constructor, and property Getters and
    Setters w/ attributes associated with
    each of them. If a Property doesn’t
    have eitehr a getter or a setter it
    will not serialize – which was a
    suprise (I imagined the default
    onstructor would ensure that the
    object had defulat values upon
    deserialization and the setters would
    update with whatever was serialized –
    but no this isn’t the case).

    Another nifty (sigh) thing about
    XmlSerialization is that the classes
    can’t be contained within a module. So
    we move the types up to a namespace…

    namespace JSONExample
        open System
        open System.IO 
        open System.Net 
        open System.Text 
        open System.Web 
        open System.Xml
        open System.Security.Authentication 
        open System.Runtime.Serialization //add assemnbly reference System.Runtime.Serialization System.Xml
        open System.Xml.Serialization
        open System.Collections.Generic 
    
        [<DataContract>]            
        type ChemicalElementRecord() =  
            [<field: DataMember(Name="name") >] 
            let mutable name: string  = ""
            
            [<field: DataMember(Name="boiling_point") >] 
            let mutable boilingPoint: string =""
    
            [<field: DataMember(Name="atomic_mass") >] 
            let mutable atomicMass: string  = ""
    
            [<XmlAttribute("name")>]
            member this.Name with get() = name and set v = name <- v
            
            [<XmlAttribute("boiling-point")>]
            member this.BoilingPoint with get()  = boilingPoint  and set v = boilingPoint <- v
    
            [<XmlAttribute("atomic-mass")>]
            member this.AtomicMass with get() = atomicMass  and set v = atomicMass <- v
        
        [<XmlRoot("freebase")>]
        [<DataContract>] 
        type FreebaseResultRecord() =  
            
            [<field: DataMember(Name="code") >] 
            let mutable code: string = ""
    
            [<field: DataMember(Name="result") >] 
            let mutable result: ChemicalElementRecord array = Array.empty
            
            [<field: DataMember(Name="message") >] 
            let mutable message: string = ""
    
            [<XmlElement("message")>] 
            member this.Message with get() : string = message and set v = message <- v
    
            [<XmlArrayAttribute("chemical-elements")>]
            [<XmlArrayItem(typeof<ChemicalElementRecord>, ElementName = "chemical-element")>]
            member this.Result with get() = result and set v = result <- v
            
            [<XmlAttribute("code")>]
            member this.Code with get() = code and set v = code <- v
     
        module Test = 
            let getJsonFromWeb() = 
                let query = "[{'type':'/chemistry/chemical_element','name':null,'boiling_point':null,'atomic_mass':null}]"
                let query = query.Replace("'","\"") 
                let queryUrl = sprintf "http://api.freebase.com/api/service/mqlread?query=%s" "{\"query\":"+query+"}" 
              
                let request : HttpWebRequest = downcast WebRequest.Create(queryUrl) 
                request.Method <- "GET" 
                request.ContentType <- "application/x-www-form-urlencoded" 
              
                let response = request.GetResponse() 
              
                let result = 
                    try 
                        use reader = new StreamReader(response.GetResponseStream()) 
                        reader.ReadToEnd(); 
                    finally 
                        response.Close() 
              
                let data = Encoding.Unicode.GetBytes(result); 
                let stream = new MemoryStream() 
                stream.Write(data, 0, data.Length); 
                stream.Position <- 0L 
                stream
    
    
              
            let test =
                // get some JSON from the web
                let stream = getJsonFromWeb()
                
                // convert the stream of JSON into an F# Record
                let JsonSerializer = Json.DataContractJsonSerializer(typeof<FreebaseResultRecord>) 
                let result: FreebaseResultRecord = downcast JsonSerializer.ReadObject(stream) 
    
                // save the Records to disk as JSON 
                use fs = new FileStream(@"C:\temp\freebase.json", FileMode.Create) 
                JsonSerializer.WriteObject(fs,result)
                fs.Close()
    
                // save the Records to disk as System Controlled XML
                let xmlSerializer = DataContractSerializer(typeof<FreebaseResultRecord>);
                use fs = new FileStream(@"C:\temp\freebase.xml", FileMode.Create) 
                xmlSerializer.WriteObject(fs,result)
                fs.Close()
    
                use fs = new FileStream(@"C:\temp\freebase-pretty.xml", FileMode.Create) 
                let xmlSerializer = XmlSerializer(typeof<FreebaseResultRecord>)
                xmlSerializer.Serialize(fs,result)
                fs.Close()
                
    
            ignore(test)
    
    
        
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Basically I have a single page on my site that I want any php
I have an XDocument class with the XML contents already made. I basically want
Basically I want get data I already have accessed from javascript and passing it
I have about 1000 folders that I want to extract a single file from
i'm experimenting with django and the builtin admin interface. I basically want to have
This is what I'm talking about: http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ComboBox/ComboBox.aspx basically I want to have a drop
I have a page where I basically want an element to 'blink' for a
I have a large multidimensional array and I basically want to drop the first
I have an SPListItemCollection. I basically want to get one of the items (randomly)
I have those two html radio buttons and textarea. I basically want to enable

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.