2017-01-13 130 views
0

我有一個JSON字符串(如下)。我想將它反序列化爲一個C#對象並將數據作爲列表獲取。我的問題是,數據在JSON數組中不可用。我怎麼需要準備我的解決方案,我可以在這個結構中獲取數據:將.JSON對象反序列化爲.Net列表(C#)

  • 傳感器
    • 傳感器1
    • 傳感器2
    • 傳感器3

傳感器1 - N的我只需要在列表中的GUID。後面的數據不相關。

在我的代碼替換了所有的GUID與「GUID」

{ 
    "object": { 
    "GUID": { 
     "type": "sensor", 
     "owner": "GUID", 
     "time": 1482499665, 
     "description": "Temperatursensor 1", 
     "sdevice": "00003639", 
     "model": "SOLUCON Industry Temperature", 
     "tag": [ 
     "GUID", 
     "GUID" 
     ] 
    }, 
    "GUID": { 
     "type": "sensor", 
     "owner": "GUID", 
     "time": 1482499758, 
     "description": "Wassersensor 1", 
     "sdevice": "000056d9", 
     "model": "SOLUCON Industry Water", 
     "tag": [ 
     "GUID", 
     "GUID" 
     ] 
    }, 
    "GUID": { 
     "type": "sensor", 
     "owner": "GUID", 
     "time": 1482499797, 
     "description": "Rauchmelder 1", 
     "sdevice": "00008519", 
     "model": "TG551A", 
     "tag": [ 
     "GUID", 
     "GUID" 
     ] 
    }, 
    "GUID": { 
     "type": "sensor", 
     "owner": "GUID", 
     "time": 1483888365, 
     "description": "SOLUCON Industry Multi 2", 
     "sdevice": "0000d409", 
     "model": "SOLUCON Industry Multi", 
     "tag": [ 
     "GUID", 
     "GUID" 
     ] 
    } 
    }, 
    "status": "ok" 
} 

回答

3

您可以使用Newtonsoft.Json包像這樣:

var jsonString = ... 
var result = JsonConvert.DeserializeObject<IDictionary<string, object>>(jsonString); 
var obj = (JObject)result["object"]; 
foreach (var prop in obj.Properties()) 
{ 
    Console.WriteLine(prop.Name); 
} 

這將打印object的所有GUID屬性節點。

如果你想獲得額外的對象,你可以定義一個模式:

public class Item 
{ 
    public string Type { get; set; } 

    public Guid Owner { get; set; } 

    public string Description { get; set; } 

    public IList<string> Tag { get; set; } 

    ... 
} 

,然後你可以得到這樣的傳感器:

foreach (var prop in obj.Properties()) 
{ 
    Console.WriteLine(prop.Name); 

    Sensor sensor = prop.Value.ToObject<Sensor>(); 
} 
1

結構你提供看起來像一本字典所以它應該反序列化到:

class Data 
{ 
    public Dictionary<Guid, Sensor> Object {get;set;} 
} 

從這裏你可以提取鍵列表(data.Object.Keys),它將包含您的Guid列表。