[英]How to convert string to list of dictionary
I have a string from http response我有一个来自 http 响应的字符串
data = "[{'value':123,'Type':'Range'},{'value':456,'Type':'Fixed'}]"
how can i convert it into list of dict in c#我如何将其转换为 C# 中的 dict 列表
There should be no issue there.那里应该没有问题。
With either deserialising it to List<customObject>
or List<Dictionary<string,string>>
将其反序列化为
List<customObject>
或List<Dictionary<string,string>>
using Json.net library.使用Json.net库。
public class Data{
public string value{get;set;}
public string Type{get;set;}
}
var testClass = JsonConvert.DeserializeObject<List<Data>>(input);
Object dump:对象转储:
Dumping object(System.Collections.Generic.List`1[Data])
[
{
Type : Range
value : 123
},
{
Type : Fixed
value : 456
}
]
Or directly :或直接:
var testDict = JsonConvert.DeserializeObject<List<Dictionary<string,string>>>(input);
Result :结果 :
Dumping object(
System.Collections.Generic.List`1[System.Collections.Generic.Dictionary`2[String,String]])
[
{
[
[value, 123]
,
[Type, Range]
] },
{
[
[value, 456]
,
[Type, Fixed]
]
}
]
Don't forget the using Newtonsoft.Json;
不要忘记
using Newtonsoft.Json;
The better way is to use simple list of object : First create class like below更好的方法是使用简单的对象列表:首先创建如下类
public class respObject
{
public int Value { get; set; }
public string Type { get; set; }
}
then DeserializeObject using Newtonsoft.Json as然后 DeserializeObject 使用 Newtonsoft.Json 作为
var data = "[{'value':123,'Type':'Range'},{'value':456,'Type':'Fixed'}]";
var objList = JsonConvert.DeserializeObject<List<respObject>>(data);
But answer to your Question list of dict但是回答你的 dict 问题列表
var data = "[{'value':123,'Type':'Range'},{'value':456,'Type':'Fixed'}]";
var listDict = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(data);
You can try with JArray
你可以试试
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.