views:

101

answers:

1
+2  Q: 

Json parsing F#

Hello,

#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 

This returns -> End element 'coordinates' from namespace '' expected. Found element 'item' from namespace ''

How can I define the DataMember coordinates so that it understands ?

Thanks a lot

+3  A: 

this works for me

#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|];}
desco
@desco , thank you for your reply, but there are no \" in the string to decode, so i need to find a way to make it work without them (other that tw.Replace("[",@"\"[").Replace("]",@"]\""), thanks !
jlezard
[-7.002648,110.449961] is not string value but array of floats, if you fix geo definition so coordinates field is float[] - it should fix this issue. I've corrected my sample to demonstrate this
desco
Thanks that works perfecto!
jlezard
@jlezard: If this is the correct answer, you're supposed to accept it. You now have an accept rate of 20%. Soon people may no longer be inclined to answer any questions you ask..
Ronald Wildenberg
@Ronald Wildenberg Accepted ! Thanks
jlezard