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?

4

2 に答える 2

3

JObject を使用するのはどうですか。

var obj = new JObject();

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

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

あなたにあげる

{"One":"Value One","Two":"Value Two","Three":"Value Three"}
于 2012-04-17T22:29:33.120 に答える
0

.net クラス ライブラリの JavascripSerializer オブジェクトを使用します。シリアル化するオブジェクトのリフレクションをサポートします

msdn ドキュメントを参照してください

于 2012-04-17T22:35:14.170 に答える