fastJSON ToJSON into dictionary?

2k Views Asked by At

How to use fastJSON (or some other JSON lib, possibly) to dump some data into a dictionary format, e.g. {"key1": "valstring", "key2": 1234}?

If I try to dump Dictionary<string, Object> I get something like [{"k":"key1","v":"valstring"},{"k":"key2","v":1234}] instead.

3

There are 3 best solutions below

1
On BEST ANSWER

We use Json.NET at our office. We send json objects between python and C#. We ran into the same problem, though ours was just the differences in how the languages naturally serialized it.

The best part about it, if I'm remember correctly, is that it had this behavior right out of the box.

var dict = new Dictionary<string, string>();
dict.Add("key", "val");
dict.Add("key2", "val2");

string json = JsonConvert.SerializeObject(dict);

Json should equal { "key": "val", "key2": "val2" }

0
On

(fastJSON) You need use some parameters parameters:

_jsonParameters = new JSONParameters
        {
            EnableAnonymousTypes = true,
            SerializeToLowerCaseNames = true,
            UseFastGuid = false,
            KVStyleStringDictionary = false <---- THIS
        };
    }

JSON.ToJSON(obj, _jsonParameters)
0
On

You just can use JavaScriptSerializer to create your solution, it's native for .Net.

var dict = new Dictionary<string, string>();
dict.Add("key", "val");
dict.Add("key2", "val2");

var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(dict);

And you'l get result you are expected: {"key1": "valstring", "key2": 1234}