2012-02-21 25 views
25

這看起來應該很容易,但是當我嘗試將一些簡單的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一個參數的構造函數?

+0

'MissingMethodException'與'string'類型(不具有無參數構造函數)相關聯,不與'JavaScriptSerializer'關聯。 – 2012-02-21 23:30:00

+0

可能的重複:http://stackoverflow.com/questions/2959605 – 2012-02-21 23:32:02

+4

無論如何'DataContractJsonSerializer'通常比'JavaScriptSerializer'更好。 – Steve 2012-02-21 23:36:18

回答

21

無參數構造函數需要任何類型的反序列化。想象一下,你正在實施一個解串器。您需要:

  1. 獲得一種從輸入流中的對象(在這種情況下,它的字符串)
  2. 實例化的對象。 如果沒有默認的構造函數,則無法做到這一點。
  3. 從流讀取屬性/值
  4. 從流分配值,我有同樣的問題在步驟2中
+12

哦,但[有一種方法](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatterservices.getuninitializedobject.aspx):) – 2014-09-09 18:39:34

+0

@LucasTrzesniewski你可以發佈這個作爲答案? – jrh 2017-10-16 17:36:44

+0

@jrh我上面的評論指的是*「你沒有辦法做到這一點,如果沒有默認構造函數」*這個答案的一部分,但它不以任何方式解決OP的問題。 – 2017-10-16 18:00:38

5

創建的對象,這是什麼固定的問題。

乾杯!

//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); 
相關問題