【发布时间】:2012-03-12 07:35:46
【问题描述】:
这看起来应该很容易,但是当我尝试将deserialize 一些简单的 JSON 转换为托管类型时,我遇到了异常。例外是:
MissingMethodException
没有为“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 需要无参数构造函数?
【问题讨论】:
-
MissingMethodException与string类型相关联(没有无参数构造函数),而不是与JavaScriptSerializer相关联。 -
DataContractJsonSerializer通常是比JavaScriptSerializer更好的选择。 -
谢谢罗伯特,我看到 System.String 没有无参数构造函数;我只是不清楚为什么这很重要。
-
谢谢史蒂夫。我无法为这个项目选择反序列化类。
标签: c# json deserialization