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

标签 c# json deserialization

这看起来应该很容易,但是当我尝试 deserialize 时遇到了异常一些简单的 JSON 转换为托管类型。异常(exception)是:

MissingMethodException
No parameterless constructor defined for type of '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 需要无参数构造函数?

最佳答案

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

  1. 从输入流中获取一种对象(在本例中为字符串)
  2. 实例化对象。 如果没有默认构造函数,你就无法做到这一点
  3. 从流中读取属性/值
  4. 将流中的值分配给第 2 步中创建的对象。

关于c# - 在 JSON 反序列化期间没有为 'System.String' 类型定义无参数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9386929/

相关文章:

c# 7.x 使用元组类型的短名称

java - 在更改单个最终字段的类型时保持 Java 序列化兼容性

c# - 如何在 Web Api Controller 中触发 OnActionExecuting?

c# - MVVM 如何以及在哪里 'Get Item By Id'

c# - 如何创建一个属性来存储另一个属性中所选值的索引?

java - spring中如何将json数据从服务器发送到客户端

python - 使用python从列表中提取Json数据

javascript - 如何使用 Typeahead.js 0.10 一步一步/远程/预取/本地

java - 将 json 数组值反序列化为特定的 Java 类字段

java - 为什么 Gson Preconditions 在这种情况下会失败?