![](/img/trans.png)
[英]Fix for no parameterless constructor defined for type of 'System.String[]' during deserialization
[英]No parameterless constructor defined for type of 'System.String' during JSON deserialization
这看起来应该很简单,但是当我尝试将一些简单的 JSON反序列化为托管类型时出现异常。 例外是:
缺少方法异常
没有为“System.String”类型定义无参数构造函数
虽然 System.String 确实没有无参数构造函数,但我不清楚为什么这很重要。
执行反序列化的代码是:
using System.Web.Script.Serialization;
private static JavaScriptSerializer serializer = new JavaScriptSerializer();
public static MyType Deserialize(string json)
{
return serializer.Deserialize<MyType>(json);
}
我的类型大致是:
public class MyType
{
public string id { get; set; }
public string type { get; set; }
public List<Double> location { get; set; }
public Address address { get; set; }
public Dictionary<string, string> localizedStrings { get; set; }
}
另一类用于地址:
public class Address
{
public string addressLine { get; set; }
public string suite { get; set; }
public string locality { get; set; }
public string subdivisionCode { get; set; }
public string postalCode { get; set; }
public string countryRegionCode { get; set; }
public string countryRegion { get; set; }
}
这是JSON:
{
"id": "uniqueString",
"type": "Foo",
"location": [
47.6,
-122.3321
]
"address": {
"addressLine": "1000 Fourth Ave",
"suite": "en-us",
"locality": "Seattle",
"subdivisionCode": "WA",
"postalCode": "98104",
"countryRegionCode": "US",
"countryRegion": "United States"
},
"localizedStrings": {
"en-us": "Library",
"en-ES": "La Biblioteca"
}
}
即使我的 JSON 只是:
{
"id": "uniquestring"
}
谁能告诉我为什么 System.String 需要无参数构造函数?
任何类型的反序列化都需要无参数构造函数。 想象一下,您正在实现一个解串器。 你需要:
我有同样的问题,这就是解决问题的方法。
干杯!
//Deserializing Json object from string
DataContractJsonSerializer jsonObjectPersonInfo =
new DataContractJsonSerializer(typeof(PersonModel));
MemoryStream stream =
new MemoryStream(Encoding.UTF8.GetBytes(userInfo));
PersonModel personInfoModel =
(PersonModel)jsonObjectPersonInfo.ReadObject(stream);
复活这个以防我自己需要它; 就我而言,错误出在 JSON 中。
我正在反序列化为List<string>
但 JSON 错误地传递了一个 ey 值对列表,例如
{
"Roles": [
{ "ID": "Administrator", "Name": "Administrator" },
{ "ID": "Client", "Name": "Client" }
]
}
进入:
public List<string> Roles { get; set; }
这会在 OP 尝试将对象反序列化为字符串时出现错误。
如果给出失败的属性名称,那将会很方便!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.