4

I have a slight situation. I'm interacting with a web service using RestSharp, where the service is requiring me to send the following as part of the request:

{
    "a":"a value",
    "b":"b value"
}

Which is all fine and dandy, because you could simply use a class such as this:

public class MyClass
{
    public string A { get; set; }
    public string B { get; set; }
}

However, I do not know know the property names at runtime. Therefore, I attempted to use an ExpandoObject, but of course, this simply serialized as a JSON array:

[
    "a":"a value",
    "b":"b value"
]

So, it would seem that I need to be able to serialize (and deserialize) a Dictionary (or IEnumerable<KeyValuePair<string, string>>) as a JSON object (in other words, use curly braces instead of a brackets).

Does anyone know how I might do this, preferably by using a Json.NET attribute, such that the functionality may be reused elsewhere?

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
cwharris
  • 17,835
  • 4
  • 44
  • 64
  • this was asked here http://stackoverflow.com/questions/3739094/serializing-deserializing-dictionary-of-objects-with-json-net – Anthony Johnston Apr 17 '12 at 22:15
  • That posters question was about the details of how to serialize a dictionary of complex objects into a Json array of Json objects. My question is about how to serialize a dictionary of simple key value pairs into a single Json object: where each key is a property name, and each value is a property value. – cwharris Apr 17 '12 at 22:19

2 Answers2

3

how about using a JObject?

var obj = new JObject();

obj["One"] = "Value One";
obj["Two"] = "Value Two";
obj["Three"] = "Value Three";

var serialized = obj.ToString(Formatting.None);

gives you

{"One":"Value One","Two":"Value Two","Three":"Value Three"}
Anthony Johnston
  • 9,405
  • 4
  • 46
  • 57
  • It's always the simple things that get you, right? Am I the only one? I'll test this and get back to you... :) – cwharris Apr 17 '12 at 22:33
  • This worked exactly as I needed it to. Since I wanted to keep my serialization code separate from my domain, I simply looped over the key value pairs I wanted to serialize as an object, and assigned each value to the corresponding JObject's index. – cwharris Apr 18 '12 at 06:01
  • While this wasn't the `Attribute` solution I was looking for, one could probably adapt some solution from this, using a custom converter. – cwharris Apr 18 '12 at 06:02
  • Agreed with @ChristopherHarris, I can't deserialize using this (or `ExpandoObject`) -- I just get empty objects back – ashes999 Apr 22 '13 at 14:52
  • try JObject.ToString(), you can specify your formatting and converters here too – Anthony Johnston Apr 23 '13 at 15:53
0

Use JavascripSerializer object from .net class libs. It supports reflection on the object it is serializing

see msdn docs

Paul Sullivan
  • 2,865
  • 2
  • 19
  • 25