如果你不知道在編譯時的結構,那麼就沒有其他辦法來序列化一個JSON string--它必須是詞典<字符串,對象>。但是,如果您使用C#4.0,則可以使用DynamicObject。由於動態類型化將類型解析延遲到運行時,如果使用此方法進行序列化,則可以將序列化對象視爲強類型對象(儘管無需編譯時支持)。這意味着你可以使用JSON式的點標記來訪問屬性:
MyDynamicJsonObject.key2
要做到這一點,你可以從DynamicObject繼承,並實現TryGetMember方法(quoted from this link, which has a full implementation):
public class DynamicJsonObject : DynamicObject
{
private IDictionary<string, object> Dictionary { get; set; }
public DynamicJsonObject(IDictionary<string, object> dictionary)
{
this.Dictionary = dictionary;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this.Dictionary[binder.Name];
if (result is IDictionary<string, object>)
{
result = new DynamicJsonObject(result as IDictionary<string, object>);
}
else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
{
result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
}
else if (result is ArrayList)
{
result = new List<object>((result as ArrayList).ToArray());
}
return this.Dictionary.ContainsKey(binder.Name);
}
}
注意動態類型目前不支持索引器表示法,因此對於數組,您需要implement a workaround using notation like this:
MyDynamicJsonObject.key2.Item(0)
它是你寫的一個固定的結構,還是你在尋找一個通用的解決方案? – McGarnagle
通用解決方案,假設我們不知道結構... – HydPhani