[英]Deserialize JSON array in c#
I have developed service which returns JSON string. 我已经开发了返回JSON字符串的服务。 Return string is as below:
返回字符串如下:
string result = [{"ID":"1","ProductName":"Canon"},{"ID":"2","ProductName":"HP"}];
Now i want to deserialize above JSON string. 现在我想反序列化上面的JSON字符串。
I have tried with below examples, but unable to do it. 我尝试了以下示例,但无法做到。 Getting error for all.
所有人都犯错误。
Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
Dictionary<string, Dictionary<string, string>> data = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(result);
string[][] data = JsonConvert.DeserializeObject<string[][]>(result);
var serialize = new JavaScriptSerializer();
string[] resultArray = serialize.Deserialize<string[]>(result);
can anyone please help me out? 有人可以帮我吗?
For example: 例如:
class Program
{
static void Main(string[] args)
{
string json = @"[{""ID"":""1"",""ProductName"":""Canon""},{""ID"":""2"",""ProductName"":""HP""}]";
IEnumerable<Product> result = JsonConvert.DeserializeObject<IEnumerable<Product>>(json);
}
}
class Product
{
public int ID { get; set; }
public string ProductName { get; set; }
}
If you want a dictionary: 如果您想要字典:
IDictionary<int, string> dict = result.ToDictionary(product => product.ID, product => product.ProductName);
There are two ways to achieve what you want either create concrete class
to store your values 有两种方法可以实现您要创建的具体
class
来存储您的值
public class MyJsonValueClass
{
[JsonProperty(PropertyName = "ID")]
public int Productid { get; set; }
[JsonProperty(PropertyName = "ProductName ")]
public string Name { get; set; }
}
List<MyJsonValueClass> jsonData = JsonConvert.DeserializeObject<List<MyJsonValueClass>>(json);
Otherwise use the List<Dictionary<string,string>>
list of dictionary will get the data if you don't want to create the class for it. 否则
List<Dictionary<string,string>>
如果您不想为其创建类,请使用List<Dictionary<string,string>>
的List<Dictionary<string,string>>
列表将获取数据。
List<Dictionary<string,string>> dataFromJson = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);
Create a class to represent each element: 创建一个代表每个元素的类:
public class TestClass
{
public int ID { get; set; }
public string ProductName { get; set; }
}
The deserialize into TestClass[]
. 反序列化为
TestClass[]
。
You can then use .ToDictionary() if you need it in that format: 然后,如果需要这种格式,可以使用.ToDictionary():
Dictionary<int, string> lookup = deserializedArray.ToDictionary(k => k.Id, v => v.ProductName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.