这看起来应该很简单,但当我try 将一些简单的JSON转换成托管类型时,我遇到了一个例外.例外情况是:

MissingMethodException

While it is true that there are no parameterless constructors for System.String, I'm not clear as to why this matters.

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:

{
    "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"
    }
}

I get the same exception even if my JSON is just:

{
    "id": "uniquestring"
}

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

推荐答案

Parameterless constructors need for any kind of deserialization. Imagine that you are implementing a deserializer. You need to:

  1. Get a type of object from the input stream (in this case it's string)
  2. Instantiate the object. You have no way to do that if there is no default constructor.
  3. 从流中读取属性/值
  4. 将流中的值分配给在步骤2创建的对象.

Json相关问答推荐

PowerShell:将Invoke-WebRequest与变量一起使用

从json数组中删除特定元素

我如何知道TJSONNumber是double还是double?

当console.log返回TRUE值时,解析的JSON中的字段未定义

NIFI-我需要数组的信息,但只需要第一个信息

如何使用 SQL Server 将 json 存储为字符串的列分解/规范化为行和列?

如何将 JSON 文本作为参数传递给 powershell?

jolt 通配符如何用于 RHS?

转义 Haskell 记录的字段

向 JSON 文件添加注释

boost::json::value 的大括号初始化将其从对象转换为数组

N1QL 搜索对象内的某些对象

如何从Typescript 中的json响应中获取日期对象

将错误消息作为 JSON 对象发送

JSON.stringify 不会转义?

如何使用 SwiftyJSON 将字符串转换为 JSON

使用 Python 3 读取 JSON 文件

Swift :将 struct 转换为 JSON?

如何从 MySQL 中检索 JSON 数据?

有没有一种快速的方法可以在文本编辑器中将 JavaScript 对象转换为有效的 JSON?