0

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.

HoverHell
  • 4,739
  • 3
  • 21
  • 23
  • Why would you want the contents of the object to be mixed up? It's fine to access them at `json[0]['k']` or `json[1]['k']`. – Shef Dec 02 '11 at 08:18

3 Answers3

1

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

Christopher Currens
  • 29,917
  • 5
  • 57
  • 77
1

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}

igofed
  • 1,402
  • 1
  • 9
  • 15
0

(fastJSON) You need use some parameters parameters:

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

JSON.ToJSON(obj, _jsonParameters)
ZOXEXIVO
  • 920
  • 9
  • 21