Decoding a Java / JSON map to an F # object

I'm having trouble converting a Java / JSON map to a useful F # object.

Here is the heart of my code:

member this.getMapFromRpcAsynchronously =
    Rpc.getJavaJSONMap (new Action<_>(this.fillObjectWithJSONMap))
    ()

member this.fillObjectWithJSONMap (returnedMap : JSONMap<string, int> option) = 
    let container = Option.get(returnedMap)
    let map = container.map
    for thing in map do
        this.myObject.add thing.key
        // do stuff with thing
    ()

The JSON returned by my RPC method is as follows:

{"id":1, "result":
    {"map":
        {"Momentum":12, "Corporate":3, "Catalyst":1},
     "javaClass":"java.util.HashMap"}
}

I am trying to map it to an F # DataContract, which looks like this:

[<DataContract>]
type JSONMap<'T, 'S> = {
    [<DataMember>]
    mutable map : KeyValuePair<'T, 'S> array
    [<DataMember>]
    mutable javaClass : string
}

[<DataContract>]
type JSONSingleResult<'T> = {
    [<DataMember>]
    mutable javaClass: string
    [<DataMember>]
    mutable result: 'T
}

Finally, the F # method that makes the actual RPC call (Rpc.getJavaJSONMap above) looks like this:

let getJavaJSONMap (callbackUI : Action<_>) = 
    ClientRpc.getSingleRPCResult<JSONSingleResult<JSONMap<string, int>>, JSONMap<string, int>>
        "MyJavaRpcClass"
        "myJavaRpcMethod"
        "" // takes no parameters
        callbackUI
        (fun (x : option<JSONSingleResult<JSONMap<string, int>>>) ->
            match x.IsSome with
                | true -> Some(Option.get(x).result)
                | false -> None 
        )

During compilation, I get no errors. My RPC method is called, and the result is returned (using Fiddler to see the actual call and return). However, it looks like F # is having JSON issues in my DataContract, since returnMap at the top is always null.

Any thoughts or advice would be greatly appreciated. Thank.

+5
2

:

open System.Web.Script.Serialization   // from System.Web.Extensions assembly

let s = @"
    {""id"":1, ""result"": 
        {""map"": 
            {""Momentum"":12, ""Corporate"":3, ""Catalyst"":1}, 
         ""javaClass"":""java.util.HashMap""} 
    } 
    "

let jss = new JavaScriptSerializer()
let o = jss.DeserializeObject(s)

// DeserializeObject returns nested Dictionary<string,obj> objects, typed
// as 'obj'... so add a helper dynamic-question-mark operator
open System.Collections.Generic 
let (?) (o:obj) name : 'a = (o :?> Dictionary<string,obj>).[name] :?> 'a

printfn "id: %d" o?id
printfn "map: %A" (o?result?map 
                   |> Seq.map (fun (KeyValue(k:string,v)) -> k,v) 
                   |> Seq.toList)
// prints:
// id: 1
// map: [("Momentum", 12); ("Corporate", 3); ("Catalyst", 1)]
+2

. :

{"map": 
        {"Momentum":12, "Corporate":3, "Catalyst":1}, 
     "javaClass":"java.util.HashMap"} 

. JSON- ( javascript ( ) ). , F #.

F # javascript.

, , .


, , JsonMap "javaclass", JSON ( ), , keyvaulepair , :

type JsonKeyValuePair<'T, 'S> =  {
    [<DataMember>] 
    mutable key : 'T
    [<DataMember>] 
    mutable value : 'S
}

type JSONMap<'T, 'S> = { 
    [<DataMember>] 
    mutable map : JsonKeyValuePair<'T, 'S> array 
} 

:

let internal deserializeString<'T> (json: string)  : 'T = 
    let deserializer (stream : MemoryStream) = 
        let jsonSerializer 
            = Json.DataContractJsonSerializer(
                typeof<'T>)
        let result = jsonSerializer.ReadObject(stream)
        result


    let convertStringToMemoryStream (dec : string) : MemoryStream =
        let data = Encoding.Unicode.GetBytes(dec); 
        let stream = new MemoryStream() 
        stream.Write(data, 0, data.Length); 
        stream.Position <- 0L
        stream

    let responseObj = 
        json
            |> convertStringToMemoryStream
            |> deserializer

    responseObj :?> 'T


let run2 () = 
    let json = "{\"map@\":[{\"key@\":\"a\",\"value@\":1},{\"key@\":\"b\",\"value@\":2}]}"
    let o  = deserializeString<JSONMap<string, int>> json
    ()

. , , -

1) .NET @ ? 2) ? , , JSON, , . .

, F # ?


:

[<DataContract>] 
type Result<'T> = { 
    [<DataMember>] 
    mutable javaClass: string 
    [<DataMember>] 
    mutable result: 'T 
} 

( - , ..):

let convertMap (json: string) = 
    let mapToken = "\"map\":"
    let mapTokenStart = json.IndexOf(mapToken)
    let mapTokenStart  = json.IndexOf("{", mapTokenStart)
    let mapObjectEnd  = json.IndexOf("}", mapTokenStart)
    let mapObjectStart = mapTokenStart
    let mapJsonOuter = json.Substring(mapObjectStart, mapObjectEnd - mapObjectStart + 1)
    let mapJsonInner = json.Substring(mapObjectStart + 1, mapObjectEnd - mapObjectStart - 1)
    let pieces = mapJsonInner.Split(',')
    let convertPiece state (piece: string) = 
        let keyValue = piece.Split(':')
        let key = keyValue.[0]
        let value = keyValue.[1]
        let newPiece = "{\"key\":" + key + ",\"value\":" + value + "}"
        newPiece :: state

    let newPieces = Array.fold convertPiece []  pieces
    let newPiecesArr = List.toArray newPieces
    let newMap = String.Join(",",  newPiecesArr)
    let json = json.Replace(mapJsonOuter, "[" + newMap + "]")
    json



let json = "{\"id\":1, \"result\": {\"map\": {\"Momentum\":12, \"Corporate\":3, \"Catalyst\":1}, \"javaClass\":\"java.util.HashMap\"} } "
printfn <| Printf.TextWriterFormat<unit>(json)
let json2 = convertMap json
printfn <| Printf.TextWriterFormat<unit>(json2)
let obj = deserializeString<Result<JSONMap<string,int>>> json2

- @ - ...


w/

let convertMapWithAmpersandWorkAround (json: string) = 
    let mapToken = "\"map\":"
    let mapTokenStart = json.IndexOf(mapToken)
    let mapObjectEnd  = json.IndexOf("}", mapTokenStart)
    let mapObjectStart = json.IndexOf("{", mapTokenStart)
    let mapJsonOuter = json.Substring(mapTokenStart , mapObjectEnd - mapTokenStart + 1)
    let mapJsonInner = json.Substring(mapObjectStart + 1, mapObjectEnd - mapObjectStart - 1)
    let pieces = mapJsonInner.Split(',')
    let convertPiece state (piece: string) = 
        let keyValue = piece.Split(':')
        let key = keyValue.[0]
        let value = keyValue.[1]
        let newPiece = "{\"key@\":" + key + ",\"value@\":" + value + "}"
        newPiece :: state

    let newPieces = Array.fold convertPiece []  pieces
    let newPiecesArr = List.toArray newPieces
    let newMap = String.Join(",",  newPiecesArr)
    let json = json.Replace(mapJsonOuter, "\"map@\":[" + newMap + "]")
    json



let json = "{\"id\":1, \"result\": {\"map\": {\"Momentum\":12, \"Corporate\":3, \"Catalyst\":1}, \"javaClass\":\"java.util.HashMap\"} } "
printfn <| Printf.TextWriterFormat<unit>(json)
let json2 = convertMapWithAmpersandWorkAround json
printfn <| Printf.TextWriterFormat<unit>(json2)
let obj = deserialize<Result<JSONMap<string,int>>> json2

:

[<DataContract>] 

.

+1

All Articles