2012-05-14 90 views
2

我使用版本4.0.8的Newtonsoft.Json並試圖將其與Web API一起使用。 所以我想反序列化JSON與使用JSON.NET反序列化字典

JsonConvert.DeserializeObject<AClass>(jsonString); 

這工作,直到我添加了一個字典財產這一類,想反序列化。

JSON字符串是在

{ 
    "Date":null, 
    "AString":"message", 
    "Attributes":[ 
        {"Key":"key1","Value":"value1"},  
        {"Key":"key2","Value":"value2"} 
       ], 
    "Id":0, 
    "Description":"... 
} 

形式當JsonSerializationException類型的反序列化異常處理消息occures:「無法反序列化JSON數組類型「System.Collections.Generic.Dictionary`2 [系統.String,System.String]'。

我在做什麼錯在這裏?

UPDATE1: 當JSON.NET序列化我得到了字典中的以下內容:

Attributes":{"key1":"value1","key2":"value2"} 

似乎的WebAPI反序列化對象比Json.Net的其他方式將。 服務器端我使用隱式反序列化下面一行:

return new HttpResponseMessage<AClass>(object); 

UPDATE2: 正如我現在來到了下面的行服務器端解決辦法。

return new HttpResponseMessage<string>(JsonConvert.SerializeObject(license).Base64Encode()); 

我使用Json.Net服務器端將其轉換爲base64編碼的字符串。所以Json.Net可以反序列化自己的格式。

但它仍然不是我想要的,那麼還有什麼進一步的建議嗎?

+1

你什麼JSON,如果你連載班上? – Rawling

+0

感謝您的快速響應。我相應地更新了我的問題。 – dasheddot

+1

除非在Web API或Newtonsoft上有一個選項來使其以「相反」方式處理字典,否則我只是建議在每一端使用相同的庫(序列化/反序列化)(如果可能的話)。 – Rawling

回答

3

如果聲明Attributes作爲List<KeyValuePair<string, string>>

1

this post它應該工作,呼籲

JsonConvert.SerializeObject(yourObject, new KeyValuePairConverter()); 

得到您的JSON中的Web API是爲您創建格式。

人體工程學,人們可能會認爲調用

JsonConvert.DeserializeObject<AClass>(jsonString, new KeyValuePairConverter()); 

會做相反,正確處理Web API的風格。

我不知道這個過載是否存在,雖然;試試看看會發生什麼......

+0

我試過了,但結果相同。即使在反串行化時應用keyvalueparallelverter也會發生相同的異常。 – dasheddot

+0

呃,夠公平的。值得一試。 – Rawling

0

如果是這樣。NET 4,你可以使用DataContract屬性和DataContractJsonSerializer Class強制執行的消息格式:

[DataContract] 
    public class Message 
    { 
     [DataMember] 
     public DateTime? Date { get; set; } 
     [DataMember] 
     public string AString { get; set; } 
     [DataMember] 
     public Dictionary<string, string> Attributes { get; set; } 
     [DataMember] 
     public int Id { get; set; } 
     [DataMember] 
     public string Description { get; set; } 
    } 

     DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Message)); 

     Message message = null; 
     using (MemoryStream jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) 
     { 
      // Deserialize 
      message = (Message)jsonSerializer.ReadObject(jsonStream); 

      // Go to the beginning and discard the current stream contents. 
      jsonStream.Seek(0, SeekOrigin.Begin); 
      jsonStream.SetLength(0); 

      // Serialize 
      jsonSerializer.WriteObject(jsonStream, message); 
      jsonString = Encoding.UTF8.GetString(jsonStream.ToArray()); 
     } 

序列化這回出產生以下JSON:

{"AString":"message","Attributes":[{"Key":"key1","Value":"value1"},{"Key":"key2","Value":"value2"}],"Date":null,"Description":"...","Id":0} 
+2

謝謝,但我想用Json.Net做到這一點,因爲我們已經在解決方案的幾個地方使用它,所以我不想真正使用.Net DataContractSerializer。 – dasheddot

1
Dictionary<string, object> result = JsonConvert.DeserializeObject<Dictionary<string, object>>(strJsonResult);