2012-07-17 21 views
0

我使用OpenRasta为我的.NET应用程序提供了一个API。OpenRasta AsJsonDataContract()字典

我使用Dictionaries时产生的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

我结束了使用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(); 
0

看看的JsonDictionary,

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

序列化之后,它出来作为

{"someName1":"someValue1","someName2":"someValue2"}