JSON反序列化中没有无参数构造函数定义的错误

时间:2015-01-13 15:56:07

标签: c# json serialization

我一直在努力找到我的JSON反序列化代码有什么问题并阅读了很多文章,但找不到确切的解决方案。 JSON由客户端发送,有时它成功,有时它会因错误而失败 “没有为'System.String'类型定义无参数构造函数。” 在这一行:RootObject myData = new JavaScriptSerializer()。Deserialize(json);

C#

DataTable dt = new DataTable();
dt.Columns.Add("isbn", typeof(string));
dt.Columns.Add("price", typeof(string));
dt.Columns.Add("uri", typeof(string));

using (var WebClient = new WebClient())
{
    string json = WebClient.DownloadString("http://www.pricetree.com/internal/test.txt");
    RootObject myData = new JavaScriptSerializer().Deserialize<RootObject>(json);

    foreach (var item in myData.results.collection1)
    {
        dt.Rows.Add(item.url, item.price, item.uri);
    }
}

班级

public class Collection1
{
    public string price { get; set; }
    public string uri { get; set; }
    public string url { get; set; }
}

public class Results
{
    public List<Collection1> collection1 { get; set; }
}

public class RootObject
{
    public string name { get; set; }
    public int count { get; set; }
    public string lastrunstatus { get; set; }   
    public string lastsuccess { get; set; }
    public Results results { get; set; }
}

我已经从下面的帖子中看到了一些答案,但是没有用。任何人都可以建议我正确的解决方案。

No parameterless constructor defined for type of 'System.String' during JSON deserialization

Screenshot for error

1 个答案:

答案 0 :(得分:4)

如果您使用这些类,它将起作用:

public class Collection1
{
    public string price { get; set; }
    public object uri { get; set; }
    public string url { get; set; }
}

public class Results
{
    public List<Collection1> collection1 { get; set; }
}

public class RootObject
{
    public string name { get; set; }
    public int count { get; set; }
    public string frequency { get; set; }
    public int version { get; set; }
    public bool newdata { get; set; }
    public string lastrunstatus { get; set; }
    public string lastsuccess { get; set; }
    public string thisversionstatus { get; set; }
    public string thisversionrun { get; set; }
    public Results results { get; set; }
}

这个站点将自动构建来自json的C#类:http://json2csharp.com/