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?

2
  • this was asked here stackoverflow.com/questions/3739094/… Commented Apr 17, 2012 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. Commented Apr 17, 2012 at 22:19

2 Answers 2

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"}
Sign up to request clarification or add additional context in comments.

5 Comments

It's always the simple things that get you, right? Am I the only one? I'll test this and get back to you... :)
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.
While this wasn't the Attribute solution I was looking for, one could probably adapt some solution from this, using a custom converter.
Agreed with @ChristopherHarris, I can't deserialize using this (or ExpandoObject) -- I just get empty objects back
try JObject.ToString(), you can specify your formatting and converters here too
0

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

see msdn docs

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.