我正在使用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"
}
]
有任何建议如何解决这个问题?
答案 0 :(得分:0)
看一下JsonDictionary,
JsonDictionary items = new JsonDictionary();
Items.Add("someName1", "someValue1");
Items.Add("someName2", "someValue2");
序列化后,它出现为
{"someName1":"someValue1","someName2":"someValue2"}
答案 1 :(得分: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();