Điều này có vẻ dễ dàng như vậy, nhưng tôi nhận được một ngoại lệ khi tôi thử một số JSON đơn giản thành một loại được quản lý. Trường hợp ngoại lệ là:Không có hàm tạo tham số nào được định nghĩa cho kiểu 'System.String' trong quá trình deserialization JSON
MissingMethodException
Không parameterless constructor định nghĩa cho loại 'System.String'
Trong khi đó là sự thật rằng không có nhà xây dựng parameterless cho System.String, tôi không rõ ràng là tại sao điều này lại quan trọng.
Các mã mà thực hiện deserialization là:
using System.Web.Script.Serialization;
private static JavaScriptSerializer serializer = new JavaScriptSerializer();
public static MyType Deserialize(string json)
{
return serializer.Deserialize<MyType>(json);
}
loại của tôi là khoảng:
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; }
}
Lớp khác là một địa chỉ:
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; }
}
Đây là 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"
}
}
tôi nhận được cùng một ngoại lệ ngay cả khi JSON của tôi chỉ là:
{
"id": "uniquestring"
}
Ai có thể cho tôi biết lý do tại sao một constructor parameterless là cần thiết cho System.String?
'MissingMethodException' được kết hợp với loại' string' (không có hàm tạo tham số), không phải với 'JavaScriptSerializer'. –
Có thể trùng lặp: http://stackoverflow.com/questions/2959605 –
'DataContractJsonSerializer' thường là một lựa chọn tốt hơn so với bất kỳ dòng chữ' JavaScriptSerializer' nào. – Steve