I am using OpenRasta provide an API for my .NET application.
I have a problem with the format of the JSON it produces when using Dictionaries.
I have the following config:
ResourceSpace.Has.ResourcesOfType<Dictionary<String,String>>()
.AtUri("/test")
.HandledBy<ProductHandler>()
.AsXmlDataContract()
.And.AsJsonDataContract();
The ProductHandler returns the following Dictionary:
Dictionary<String, String> dict = new Dictionary<string, string>();
dict.Add("foo1", "bar1");
dict.Add("foo2", "bar2");
dict.Add("foo3", "bar3");
I would like the following JSON:
{
"foo1": "bar1",
"foo2": "bar2",
"foo3": "bar3"
}
But instead I get the following:
[
{
"Key": "foo1",
"Value": "bar1"
},
{
"Key": "foo2",
"Value": "bar2"
},
{
"Key": "foo3",
"Value": "bar3"
}
]
Any suggestions how to fix this?
I ended up using the Newtonsoft.Json library for serialization, which provides the format I wanted.
The code for the codec is:
[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);
}
}
}
And the config looks like:
ResourceSpace.Uses.UriDecorator<ContentTypeExtensionUriDecorator>();
ResourceSpace.Has.ResourcesOfType<MeasurementDataFile[]>()
.AtUri("/test")
.HandledBy<MeasurementHandler>()
.TranscodedBy<NewtonsoftJsonCodec>()
.And.AsXmlDataContract();