问题描述
这看起来应该是很容易的,但我得到一个例外,当我尝试的一些简单的JSON到一个托管类型。唯一的例外是:
This seems like it should be so easy, but I am getting an exception when I try to deserialize some straightforward JSON into a managed type. The exception is:
MissingMethodException结果
类型'System.String
虽然这是事实,有对System.String无参数构造函数,我并不清楚为什么这个问题。
While it is true that there are no parameterless constructors for System.String, I'm not clear as to why this matters.
执行反序列化的code是:
The code that performs the deserialization is:
using System.Web.Script.Serialization;
private static JavaScriptSerializer serializer = new JavaScriptSerializer();
public static MyType Deserialize(string json)
{
return serializer.Deserialize<MyType>(json);
}
我喜欢的类型大致是:
My type is roughly:
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:
Here's the 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仅仅是:
I get the same exception even if my JSON is just:
{
"id": "uniquestring"
}
任何人可以告诉我为什么是需要System.String一个参数的构造函数?
Can anybody tell me why a parameterless constructor is needed for System.String?
推荐答案
参数构造函数需要任何形式的反序列化。试想一下,你正在实施一个解串器。您需要:
Parameterless constructors need for any kind of deserialization. Imagine that you are implementing a deserializer. You need to:
- 获取一个类型从输入流对象(在这种情况下,它的字符串)
- 实例化的对象。的你没有办法做到这一点,如果没有默认的构造函数的
- 读取性能/从流值
- 从流上的步骤2中创建的对象分配的值。
- Get a type of object from the input stream (in this case it's string)
- Instantiate the object. You have no way to do that if there is no default constructor.
- Read the properties/value from stream
- Assign the values from the stream to the object created on step 2.
这篇关于JSON反序列化过程中类型'System.String'的定义没有参数的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!