[英]How to convert string to list of dictionary
我有一個來自 http 響應的字符串
data = "[{'value':123,'Type':'Range'},{'value':456,'Type':'Fixed'}]"
我如何將其轉換為 C# 中的 dict 列表
那里應該沒有問題。
將其反序列化為List<customObject>
或List<Dictionary<string,string>>
使用Json.net庫。
public class Data{
public string value{get;set;}
public string Type{get;set;}
}
var testClass = JsonConvert.DeserializeObject<List<Data>>(input);
對象轉儲:
Dumping object(System.Collections.Generic.List`1[Data])
[
{
Type : Range
value : 123
},
{
Type : Fixed
value : 456
}
]
或直接:
var testDict = JsonConvert.DeserializeObject<List<Dictionary<string,string>>>(input);
結果 :
Dumping object(
System.Collections.Generic.List`1[System.Collections.Generic.Dictionary`2[String,String]])
[
{
[
[value, 123]
,
[Type, Range]
] },
{
[
[value, 456]
,
[Type, Fixed]
]
}
]
不要忘記using Newtonsoft.Json;
更好的方法是使用簡單的對象列表:首先創建如下類
public class respObject
{
public int Value { get; set; }
public string Type { get; set; }
}
然后 DeserializeObject 使用 Newtonsoft.Json 作為
var data = "[{'value':123,'Type':'Range'},{'value':456,'Type':'Fixed'}]";
var objList = JsonConvert.DeserializeObject<List<respObject>>(data);
但是回答你的 dict 問題列表
var data = "[{'value':123,'Type':'Range'},{'value':456,'Type':'Fixed'}]";
var listDict = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(data);
你可以試試JArray
var data = "[{'value':123,'Type':'Range'},{'value':456,'Type':'Fixed'}]";
var dict = JArray.Parse(data)
.ToDictionary(k => k["value"].ToString(), v => v["Type"].ToString());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.