I have a string from http response
data = "[{'value':123,'Type':'Range'},{'value':456,'Type':'Fixed'}]"
how can i convert it into list of dict in c#
There should be no issue there.
With either deserialising it to List<customObject>
or List<Dictionary<string,string>>
using Json.net library.
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;
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
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
var data = "[{'value':123,'Type':'Range'},{'value':456,'Type':'Fixed'}]";
var listDict = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(data);
You can try with 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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.