json对象和对象为json

时间:2018-03-15 02:20:12

标签: json f#

在本教程的F#snippets http://www.fssnip.net/1l/title/Convert-an-object-to-json-and-json-to-object

上下文中

让我们说一个人类型

type Person = {
    entityName: string; 
    entityType: string; 
}

和调用Web服务并转换为json的代码。

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

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

let requestToken (): Token =        
    let url = "http://example.com"

    let request = WebRequest.Create(url) :?> HttpWebRequest
    request.Method <- "POST"
    request.Accept <- "application/json;charset=UTF-8"

    let response = request.GetResponse() :?> HttpWebResponse
    use reader = new StreamReader(response.GetResponseStream())

    let body = reader.ReadToEnd()
    Console.WriteLine body // result OK
    let result = unjson<Person> body

JSON

{
    "entityName": "john doe",
    "entityType": "client"
}

错误

  

System.Runtime.Serialization.SerializationException:无法反序列化数据协定类型“Person”,因为找不到所需的数据成员'entityName @,entityType @'。

  1. 如果有人可以添加一个示例来说明如何调用'json'函数传递result对象以将对象转换回JSON字符串

  2. type是否需要按照JSON模式包含所有字段,还是可以选择省略非必填字段?

1 个答案:

答案 0 :(得分:1)

这将使用DataContractSerializer将您的记录序列化为JSON。您需要添加一些属性才能生效。

#r "System.Runtime.Serialization" 
open System.IO
open System.Runtime.Serialization.Json
open System.Runtime.Serialization

[<DataContract>]
[<CLIMutable>]
type Person = {
    [<DataMember(Name="Name") >]
    entityName: string 
    [<DataMember(Name="Type") >]
    entityType: string 
}

let person = {entityName = "ENTITY"; entityType ="TYPE"}


let  toJson<'t> (myObj:'t) =   
    let fs = new FileStream(@"C:\tmp\test.json",FileMode.Create)
    (new DataContractJsonSerializer(typeof<'t>)).WriteObject(fs,myObj)

toJson<Person> person

这是我在test.json文件中得到的输出:

  

{ “名称”: “实体”, “类型”: “TYPE”}