在JSON反序列化期间,没有为'System.String'类型定义无参数构造函数

Jus*_* R. 28 c# json deserialization

这看起来应该很容易,但是当我尝试一些简单的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);
}
Run Code Online (Sandbox Code Playgroud)

我的类型大致是:

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; }
}
Run Code Online (Sandbox Code Playgroud)

另一个类是一个地址:

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; }
}
Run Code Online (Sandbox Code Playgroud)

这是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"
    }
}
Run Code Online (Sandbox Code Playgroud)

即使我的JSON只是:我得到了相同的异常:

{
    "id": "uniquestring"
}
Run Code Online (Sandbox Code Playgroud)

谁能告诉我为什么System.String需要无参数构造函数?

Ser*_*kin 23

无参数构造函数需要任何类型的反序列化.想象一下,您正在实现一个反序列化器.你需要:

  1. 从输入流中获取一种对象(在本例中为字符串)
  2. 实例化对象.如果没有默认构造函数,则无法执行此操作.
  3. 从流中读取属性/值
  4. 将流中的值分配给在步骤2中创建的对象.

  • 哦,但[有一种方法](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatterservices.getuninitializedobject.aspx):) (14认同)

小智 6

我有同样的问题,这就解决了这个问题.

干杯!

//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);
Run Code Online (Sandbox Code Playgroud)