2013-02-12 47 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}} 

我錯過了什麼?

相關問題