2010-08-24 40 views
11

r @ "NETFramework \ v4.0 \ Hồ sơ \ Khách hàng \ 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 

này trả -> End yếu tố 'phối' từ không gian tên '' dự kiến . Đã tìm thấy phần tử 'item' từ không gian tên ''Json phân tích F #

Làm cách nào để xác định tọa độ DataMember để nó hiểu?

Thanks a lot

Trả lời

8

Reference System.Runtime.Serialization và System.Xml

(Interactive: #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 
+0

cám ơn vì cái này – jlezard

6

làm việc này cho tôi

#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|];} 
+0

cảm ơn bạn đã trả lời, nhưng không có \ "trong chuỗi giải mã, vì vậy tôi cần tìm cách để làm cho nó hoạt động ithout chúng (khác mà tw.Replace ("[", @ "\" [") .Thay thế ("] ", @"] \ ""), cảm ơn! – jlezard

+0

[-7.002648,110.449961] không phải là giá trị chuỗi nhưng mảng nổi, nếu bạn sửa định nghĩa địa lý để trường tọa độ là nổi [] - nó sẽ khắc phục vấn đề này. Tôi đã sửa mẫu của mình để chứng minh điều này – desco

+0

Cảm ơn bạn đã làm việc hoàn hảo! – jlezard