2014-06-12 113 views
3
CLR對象

我有以下的有效載荷JSON:反序列化已知和未知的JSON領域與JSON.NET

{ 
    "id": 1, 
    "foo": "bar", 
    "bar": "foo", 
    "attr_1": ["foo", "bar"], 
    "attr_2": ["foo2", "bar2"] 
} 

我也有以下CLR對象:

public class Obj 
{ 
    public int Id { get; set; } 
    public string Foo { get; set; } 
    public string Bar { get; set; } 

    [JsonExtensionData] 
    public IDictionary<string, string[]> Properties { get; set; } 
} 

如果我嘗試反序列化它,它會失敗:

using (FileStream file = File.Open(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "file.txt"), FileMode.Open)) 
using (StreamReader reader = new StreamReader(file)) 
{ 
    Obj foo = JsonConvert.DeserializeObject<Obj>(reader.ReadToEnd()); 
} 

There is already an answer to a similar question。但是,這不是逐個讀取和寫入每個字段的解決方案。將剩餘字段反序列化爲IDictionary<string, string[]>的最佳方式是什麼?

回答

3

This line在Json.NET源代碼中強制值類型爲JToken。我認爲最簡單的方法是爲序列化創建另一種類型。

public class SerializationModel 
{ 
    public int Id { get; set; } 
    public string Foo { get; set; } 
    public string Bar { get; set; } 

    [JsonExtensionData] 
    public IDictionary<string, JToken> Properties { get; set; } 
} 

class Model 
{ 
    public int Id { get; set; } 
    public string Foo { get; set; } 
    public string Bar { get; set; } 
    public Dictionary<string, string[]> Properties { get; set; } 
} 

[Test] 
public void DeserializeTest() 
{ 
    string data = File.ReadAllText("data.txt"); 
    SerializationModel serializationModel = JsonConvert.DeserializeObject<SerializationModel>(data); 

    Model model = new Model 
    { 
     Id = serializationModel.Id, 
     Foo = serializationModel.Foo, 
     Bar = serializationModel.Bar, 
     Properties = serializationModel.Properties.ToDictionary(item => item.Key, pair => pair.Value.ToObject<string[]>()) 
    }; 

} 
+1

謝謝!這當然是一個解決方案,但並不像我想要的那麼幼稚:我會試着看看我是否可以擴展或重新實現'JsonExtensionData'。 – tugberk