0

我正在使用 OpenRasta 为我的 .NET 应用程序提供 API。

我在使用字典时生成的 JSON 格式有问题。

我有以下配置:

 ResourceSpace.Has.ResourcesOfType<Dictionary<String,String>>()
.AtUri("/test")
.HandledBy<ProductHandler>()
.AsXmlDataContract()
.And.AsJsonDataContract();

ProductHandler 返回以下字典:

        Dictionary<String, String> dict = new Dictionary<string, string>();
        dict.Add("foo1", "bar1");
        dict.Add("foo2", "bar2");
        dict.Add("foo3", "bar3");

我想要以下 JSON:

{
    "foo1": "bar1",
    "foo2": "bar2",
    "foo3": "bar3"
}

但相反,我得到以下信息:

[
    {
        "Key": "foo1",
        "Value": "bar1"
    },
    {
        "Key": "foo2",
        "Value": "bar2"
    },
    {
        "Key": "foo3",
        "Value": "bar3"
    }
]

任何建议如何解决这个问题?

4

2 回答 2

0

看看JsonDictionary,

JsonDictionary items = new JsonDictionary();
Items.Add("someName1", "someValue1");
Items.Add("someName2", "someValue2");

序列化后它出来为

{"someName1":"someValue1","someName2":"someValue2"}
于 2012-07-27T13:00:55.527 回答
0

我最终使用Newtonsoft.Json库进行序列化,它提供了我想要的格式。

编解码器的代码是:

[MediaType("application/json;q=0.3", "json")]
[MediaType("text/html;q=0.3", "html")]
public class NewtonsoftJsonCodec : IMediaTypeReader, IMediaTypeWriter
{
    public object Configuration { get; set; }

    public object ReadFrom(IHttpEntity request, IType destinationType, string destinationName)
    {
        using (var streamReader = new StreamReader(request.Stream))
        {
            var ser = new JsonSerializer();

            return ser.Deserialize(streamReader, destinationType.StaticType);
        }

    }

    public void WriteTo(object entity, IHttpEntity response, string[] parameters)
    {
        if (entity == null)
            return;
        using (var textWriter = new StreamWriter(response.Stream))
        {
            var serializer = new JsonSerializer();
            serializer.NullValueHandling = NullValueHandling.Include;
            serializer.Serialize(textWriter, entity);
        }
    }
}

配置看起来像:

ResourceSpace.Uses.UriDecorator<ContentTypeExtensionUriDecorator>();
ResourceSpace.Has.ResourcesOfType<MeasurementDataFile[]>()
    .AtUri("/test")
    .HandledBy<MeasurementHandler>()
    .TranscodedBy<NewtonsoftJsonCodec>()
    .And.AsXmlDataContract();
于 2012-07-29T03:15:31.863 回答