2013-02-12 48 views
0

我有一个Web API项目,它将JSON中定义为以下内容的对象进行水合。我试图将这个对象插入到RavenDB数据库中,但是我发现动态属性'Content'没有正确序列化(注意空数组)。将动态属性序列化为JSON

我已经尝试了几个序列化器来生成json strins:System.Helpers.Json.Encode(),System.Web.Script.Serialization.JavaScriptSerializer。两者都遭受同样的问题。

RavenJObject.fromObject(obj)遭受同样的问题。

尽管CLR反射有明显的局限性,但是有什么方法可以实现我的目标?

public class SampleType 
    { 
     public Guid? Id { get; private set; } 
     public dynamic Content { get; set; } 
     public string Message { get; set; } 
     public string Actor { get; set; } 

     public LogEntry() 
     { 
      Id = Guid.NewGuid(); 
     } 
    } 

JSON submitted to API: 
{ 
    "Content": { 
     "SomeNumber": 5, 
     "ADate": "/Date(1360640329155)/", 
     "MaybeABoolean": true, 
     "EmptyGUID": "00000000-0000-0000-0000-000000000000" 
    }, 
    "Message": "Hey there", 
    "Actor": "John Dow" 
} 

Hydrated object: 
    ID: {b75d9134-2fd9-4c89-90f7-a814fa2f244d} 
    Content: { 
     "SomeNumber": 5, 
     "ADate": "2013-02-12T04:37:44.029Z", 
     "MaybeABoolean": true, 
     "EmptyGUID": "00000000-0000-0000-0000-000000000000" 
    } 
    Message: "Hey there", 
    Actor: "John Dow" 

JSON from all three methods: 
{ 
    "Id": "b75d9134-2fd9-4c89-90f7-a814fa2f244d", 
    "Content": [ 
     [ 
      [] 
     ], 
     [ 
      [] 
     ], 
     [ 
      [] 
     ], 
     [ 
      [] 
     ] 
    ], 
    "Message": "Hey there", 
    "Actor": "John Dow" 
} 

回答

0

您的动态对象必须正确实现GetDynamicFieldNames()方法才能使动态序列化工作。

+0

这是关键。我结束了使用ExpandoObject类型。 – ebpa 2013-02-15 23:53:12

0

对于这个Servicestack.Text,您可以使用Planet最快的图书馆。您的问题的解决方案已被回答here

2

正如我记得我们使用了Newtonsoft JSON序列化程序,它很好地处理了动态和Expando对象。

0

我真的不知道你在做什么。

public class Foo 
{ 
    public dynamic Bar { get; set; } 
} 

var foo = new Foo { Bar = new { A = 1, B = "abc", C = true } }; 
Debug.WriteLine(RavenJObject.FromObject(foo).ToString(Formatting.None)); 
Debug.WriteLine(JsonConvert.SerializeObject(foo, Formatting.None)); 

这两个的输出是:

{"Bar":{"A":1,"B":"abc","C":true}} 

我错过了什么?

相关问题