[英]How can I deserialize my string into JSON?
我的想法是我要獲取我的字符串,將其轉換為JSON對象,然后遍歷results
數組以提取所有id
字段並將它們放在單獨的數組中。
我已經嘗試了多個“ C#字符串轉換為JSON示例”,但是在這部分特定代碼中使用得最遠。
主要:
String myString = "{
"total": 111,
"token": "abcdefghijklmn",
"results": [
{
"id": "001",
"some_stuff": {
"aValue": 0,
"bValue": 1
}
},
{
"id": "001",
"some_stuff": {
"aValue": 0,
"bValue": 1
}
},
{
"id": "001",
"some_stuff": {
"aValue": 0,
"bValue": 1
}
},
],
"whatdidido": {
"iretrieved": "yes"
}
}";
var list = JsonConvert.DeserializeObject<List<IdReturn>>(myString);
類:
public class IdReturn
{
public int total { get; set; }
public string token { get; set; }
public List<Attribute> results { get; set; }
}
public class results
{
public string id { get; set; }
public string some_stuff { get; set; }
}
預期的結果是一個JSON對象,我可以將其用作:list.results [i] .id以獲取每個id。 從上面的代碼中得到的錯誤消息是:
未處理的異常:Newtonsoft.Json.JsonSerializationException:無法將當前JSON對象(例如{“ name”:“ value”})反序列化為類型'System.Collections.Generic.List`1 [myExample.IdReturn]',因為該類型需要一個JSON數組(例如[1,2,3])可正確反序列化。 要解決此錯誤,可以將JSON更改為JSON數組(例如[1,2,3]),也可以更改反序列化類型,使其成為普通的.NET類型(例如,不像整數這樣的原始類型,也不像這樣的集合類型)數組或列表),可以從JSON對象反序列化。 還可以將JsonObjectAttribute添加到類型中,以強制其從JSON對象反序列化。
首先,您的字符串未寫為有效的C#,應為:
String myString = @"{
""total"": 111,
""token"": ""abcdefghijklmn"",
""results"": [
{
""id"": ""001"",
""some_stuff"": {
""aValue"": 0,
""bValue"": 1
}
},
{
""id"": ""001"",
""some_stuff"": {
""aValue"": 0,
""bValue"": 1
}
},
{
""id"": ""001"",
""some_stuff"": {
""aValue"": 0,
""bValue"": 1
}
},
],
""whatdidido"": {
""iretrieved"": ""yes""
}
}";
接下來,您需要一組類來表示JSON結構:
public class Rootobject
{
public int total { get; set; }
public string token { get; set; }
public Result[] results { get; set; }
public Whatdidido whatdidido { get; set; }
}
public class Whatdidido
{
public string iretrieved { get; set; }
}
public class Result
{
public string id { get; set; }
public Some_Stuff some_stuff { get; set; }
}
public class Some_Stuff
{
public int aValue { get; set; }
public int bValue { get; set; }
}
最后要反序列化並打印每個id
您可以執行以下操作:
var root = JsonConvert.DeserializeObject<Rootobject>(myString);
Console.WriteLine(string.Join(",", root.results.Select(item => item.id)));
對於您的示例,這將導致:
001,001,001
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.