Json разбор F #

г @ "NetFramework\v4.0\Профиль\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 

Это возвращает → Конечный элемент "координаты" из пространства имен "" ожидается. Найден элемент 'item' из пространства имен ''

Как я могу определить координаты DataMember так, чтобы он понимал?

Спасибо большое

Ответ 1

Reference 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

Ответ 2

это работает для меня

#r "System.Runtime.Serialization"

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

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


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]
    }"

let v = decode tw // val v : geo = {t = "Point"; coordinates = [|-7.002648; 110.449961|];}