有沒有人有任何使用System.Runtime.Serialization.Json和DataContracts的經驗?我有一個Perl腳本,我轉換到C#,我似乎無法弄清楚如何製作這個DataContract來說明來自網站的響應是一堆對象的事實。我試圖假裝對象不存在,我試圖定義一個合約,指定出來的第一個對象字符串,但我無法解析任何單獨的數據位。以下是200個對象中的2個樣本,這些對象將作爲請求的響應返回。C#解碼JSON - 所有對象都具有相同的唯一名稱
當前數據契約嘗試:
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(JsonMachines));
JsonMachines machines = (JsonMachines)ser.ReadObject(resp.GetResponseStream());
[DataContract]
class JsonMachines
{
[DataMember]
public JsonMachine dc54806f4fe34cf5a83b0676555f8658;
}
[DataContract]
class JsonMachine
{
[DataMember]
public string guid;
[DataMember]
public int lost_contact;
[DataMember]
public string org;
[DataMember]
public string timezone;
}
JSON響應從服務器:
{
"dc54806f4fe34cf5a83b0676555f8658" : {
"shadowprotect" : {
"jobs" : [],
"version" : {
"is_expired" : false,
"is_running" : true,
"lang" : "en",
"is_installed" : true,
"version" : "6.0.8",
"is_trial" : false,
"name" : "ShadowProtect SPX",
"is_msp" : false,
"company" : ""
}
},
"lost_contact" : 0,
"org" : "site : name",
"timezone" : -18000,
"status" : "ok",
"name" : "MACHINENAME2",
"tags" : [],
"machine_details" : {
"last_boot" : "2016-01-21T10:54:11.557000",
"volumes" : [
{
"mountpoint" : "C:\\",
"device" : "\\\\?\\Volume{07897f98-6618-11e5-8055-806e6f6e6963}\\",
"size" : 305242,
"boot" : false,
"readonly" : false,
"removable" : false,
"os_vol" : true,
"used" : 57787,
"label" : ""
},
{
"mountpoint" : null,
"device" : "\\\\?\\Volume{07897f99-6618-11e5-8055-806e6f6e6963}\\",
"size" : 99,
"boot" : false,
"readonly" : false,
"removable" : false,
"os_vol" : false,
"used" : 28,
"label" : "System Reserved"
}
],
"ram" : 3945
},
"imagemanager" : {
"folders" : []
}
},
"c947116fc62c40c2932e850944f78550" : {
"shadowprotect" : {
"jobs" : [],
"version" : {
"is_expired" : true,
"is_running" : true,
"days_to_expire" : 0,
"lang" : "en",
"is_installed" : true,
"version" : "4.2.7.19756",
"name" : "ShadowProtect",
"is_msp" : true,
"company" : null
}
},
"lost_contact" : 0,
"org" : "site : name2",
"timezone" : -18000,
"status" : "ok",
"name" : "MACHINENAME",
"tags" : [],
"machine_details" : {
"last_boot" : "2016-01-28T08:34:54.486000",
"volumes" : [
{
"mountpoint" : "C:\\",
"device" : "\\\\?\\Volume{bcbc546f-291f-11e2-9a3f-806e6f6e6963}\\",
"size" : 476153,
"boot" : false,
"readonly" : false,
"removable" : false,
"os_vol" : true,
"used" : 145434,
"label" : "OS"
},
{
"mountpoint" : null,
"device" : "\\\\?\\Volume{bcbc546e-291f-11e2-9a3f-806e6f6e6963}\\",
"size" : 745,
"boot" : false,
"readonly" : false,
"removable" : false,
"os_vol" : false,
"used" : 224,
"label" : "RECOVERY"
}
],
"ram" : 4052
},
"imagemanager" : {
"folders" : []
}
}
}
感謝這個jeromeyers的洞察力,這是我甚至不知道我不得不看。來自Perl它把所有東西都放到一個散列中,我可以隨意查詢這些散列。我拿走了邁克爾提出的一些代碼,但它並沒有解決我遇到的第一個問題,即無法讀取對象。你會注意到他將這個類標記爲第一個對象的名字,但是因爲它在每個對象之間都發生了變化,所以我不知道如何解釋它。 –