gpt4 book ai didi

Json 解析 F#

转载 作者:行者123 更新时间:2023-12-04 02:00:44 25 4
gpt4 key购买 nike

r@".NETFramework\v4.0\Profile\Client\System.Runtime.Serialization.dll"

open System.Runtime.Serialization
open System.Runtime.Serialization.Json

[<DataContract>]
type geo = {
[<field: DataMember(Name = "type")>]
t:string
[<field: DataMember(Name = "coordinates")>]
coordinates:string
}


let decode (s:string) =
let json = new DataContractJsonSerializer(typeof<geo>)
let byteArray = Encoding.UTF8.GetBytes(s)
let stream = new MemoryStream(byteArray)
json.ReadObject(stream) :?> geo

let tw = {"type":"Point","coordinates":[-7.002648,110.449961]}

decode tw
这返回->
来自命名空间 '' 的结束元素 'coordinates' 预期。从命名空间 '' 中找到元素 'item'
如何定义 DataMember 坐标以便它理解?
非常感谢

最佳答案

引用 System.Runtime.Serialization 和 System.Xml

(互动:#r "System.Runtime.Serialization")

open System.IO
open System.Runtime.Serialization.Json
open System.Xml
open System.Text

/// 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

关于Json 解析 F#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3555960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com