考慮以下JSON:創建JSON反序列化類
{
"Code": 2,
"Body": {
"Dynamic-Key": {
"Key1": "Val1",
"Key2": "Val2"
}
}
}
定義以下類的結構:
[DataContract]
class JsonResponse
{
[DataMember]
public string Code { get; set; }
[DataMember]
public JsonResponseBody Body { get; set; }
}
[DataContract]
class JsonResponseBody
{
[DataMember(Name = "Dynamic-Key")]
public DynamicKeyData Data { get; set; }
}
[DataContract]
class DynamicKeyData
{
[DataMember]
public string Key1 { get; set; }
[DataMember]
public string Key2 { get; set; }
}
我可以用下面的代碼反序列化給定的JSON:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JsonResponse));
JsonResponse responseData = serializer.ReadObject(responseStream) as JsonResponse;
但在我的情況下,「動態密鑰」不知道n並且由用戶輸入值定義。 處理這種JSON定義的正確方法是什麼?
注意事項:
的JSON是一個第三方的API,因此更改它不是一個選項。
在我的情況下,我不關心動態密鑰的名稱,所以如果有一個選項總是映射到一個通用名稱,它將完成這項工作。
在此先感謝。