1
class Foo
{
    public string Name { get; set; }
    public IDictionary<string, object> Attributes { get; set; }
}

[ServiceContract]
interface IFooService
{
    [OperationContract]
    [WebInvoke(
        Method = "GET",
        UriTemplate = "testfoo",
        ResponseFormat = WebMessageFormat.Json)]
    Foo GetTestFoo();
}

class FooService : IFooService
{
    Foo GetTestFoo()
    {
        var foo = new Foo { Name = "name" };
        foo.Attributes.Add("foo", "bar");

        var serialize = new JavaScriptSerializer().Serialize(foo);
        Debug.WriteLine(serialize); // <- good format

        return foo;
    }
}

/testfoo在 Chrome 休息客户端中调用Debug.WriteLine打印:

{"Name":"name","Attributes":{"foo":"bar"}}

但实际响应的格式如下:

{"Name":"name","Attributes":[{"Key":"foo","Value":"bar"}]}

我更喜欢第一个变体。如何配置或控制序列化以实现此目的?

4

0 回答 0