如何将JSON对象数组反序列化为c#结构

本文关键字:反序列化 结构 数组 对象 JSON | 更新日期: 2023-09-27 17:49:56

我有一个json字符串,是通过序列化对象数组创建的:

[
    {
        "html": "foo"
    },
    {
        "html": "bar"
    }
]

我如何将它反序列化为一些可迭代的c#结构?我已经尝试过这个代码,但我得到No parameterless constructor defined for type of 'System.String'.错误:

string[] htmlArr = new JavaScriptSerializer().Deserialize<String[]>(html);

我想要接收的是一个可迭代的结构来获取每个'html'对象。

如何将JSON对象数组反序列化为c#结构

为每个JSON对象使用一个类。例子:

public class HtmlItem
{
   [DataMember(Name = "html")]
   public string Html { get; set; }
}
JavaScriptSerializer ser = new JavaScriptSerializer();          
// Serialize
string html = ser.Serialize(new List<HtmlItem> {
   new HtmlItem {  Html = "foo" },
   new HtmlItem {  Html = "bar" }
});
// Deserialize and print the html items.        
List<HtmlItem> htmlList = ser.Deserialize<List<HtmlItem>>(html);
htmlList.ForEach((item) => Console.WriteLine(item.Html)); // foo bar

您可以使用Newtonsoft Json。. NET(可从NuGet获得)

string json = @"[{""html"": ""foo""},{""html"": ""bar""}]";
var items = JsonConvert.DeserializeObject<List<Item>>(json);

,

public class Item
{
    public string Html { get; set; }
}

文档站点现在显然不能工作…但我会尝试使用JSON。. NET (http://james.newtonking.com/projects/json/help/)

有几种方法可以做到这一点。你可以用不严格类型的动态方式反序列化或者你可以定义一个与json对象完全匹配的对象并反序列化到那个。如果你需要序列化多种JSON格式,我建议你使用模式。

nekman的答案不完全正确,属性应该是jsonproperty而不是DataMember。(在这种情况下,您可以删除该属性,因为反序列化器并不关心大写H)

public class HtmlItem
{
   [JsonProperty("html")]
   public string Html { get; set; }
}
JavaScriptSerializer ser = new JavaScriptSerializer();          
// Serialize
string html = ser.Serialize(new List<HtmlItem> {
   new HtmlItem {  Html = "foo" },
   new HtmlItem {  Html = "bar" }
});
// Deserialize and print the html items.        
List<HtmlItem> htmlList = ser.Deserialize<List<HtmlItem>>(html);
htmlList.ForEach((item) => Console.WriteLine(item.Html)); // foo bar