這看起來應該很容易,但是當我嘗試將一些簡單的JSON轉換爲託管類型時,我收到了一個異常。唯一的例外是:在JSON反序列化過程中爲'System.String'類型定義了沒有無參數的構造函數
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);
}
我喜歡的類型大致是:
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一個參數的構造函數?
'MissingMethodException'與'string'類型(不具有無參數構造函數)相關聯,不與'JavaScriptSerializer'關聯。 – 2012-02-21 23:30:00
可能的重複:http://stackoverflow.com/questions/2959605 – 2012-02-21 23:32:02
無論如何'DataContractJsonSerializer'通常比'JavaScriptSerializer'更好。 – Steve 2012-02-21 23:36:18