Search code examples
genericsasp.net-coref#deserializationjson-deserialization

How to use DataContractJsonSerializer with Generics


I found this example at Convert an object to json, and json to object to deserializing string to JSON while passing the type and vice versa.

/// Object to Json 
let internal json<'t> (myObj:'t) =   
        use ms = new MemoryStream() 
        (new DataContractJsonSerializer(typeof<'t>)).WriteObject(ms, myObj) 
        Encoding.Default.GetString(ms.ToArray()) 


/// Object from Json 
let internal unjson<'t> (jsonString:string)  : 't =  
        use ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(jsonString)) 
        let obj = (new DataContractJsonSerializer(typeof<'t>)).ReadObject(ms) 
        obj :?> 't

Context:

For a type Document

[<DataContract>]
type Document = {
    [<field: DataMemberAttribute(Name="name")>]
    Name: string

    [<field: DataMemberAttribute(Name="version")>]
    Version: string
}

JSON

let str = """{"name: "test"; version="97234982734"}"""

Question

How to call json and unjson functions using my example?

Why are the functions specified as internal?


Solution

  • To do this sort of operation, I typically use: System.Web.Extensions.JavaScriptSerializer class. It's got easy to use Serialize and Deserialize methods which work well with Generics.

    You'll need to include a reference to the System.Web.Extensions assemblies.

    Msdn link: https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

    No, WCF attributes ( i.e. DataContract or DataMember) are required.

    The way I understand it the serializer classes youre trying to use are used in the WCF internal for serialization.

    Code sample:

    /// Object to Json 
    let internal json<'t> (myObj:'t) =   
         let ser = new System.Web.Script.Serialization.JavaScriptSerializer()   
         ser.Serialize(myObj)
    
    /// Object from Json 
    let internal unjson<'t> (jsonString:string)  : 't =  
        let ser = new System.Web.Script.Serialization.JavaScriptSerializer() 
        let obj = ser.Deserialize<'t>(jsonString)
        obj
    

    EDIT

    If you are using .NET Core, you will not have access to this assembly. Please see this post, for an alternative approach using Newtonsoft.Json