![](/img/trans.png)
[英]ServiceStack.Text.JsonSerializer.DeserializeFromString<T>() fails to deserialize if string contains \n's
[英]ServiceStack Json DeserializeFromString<Dictionary<string, string>>() vs JsonObject.Parse()
乍一看,它們似乎是同一回事。 因為JsonObject : IDictionary<string, string>
。 但是,當我嘗試反序列化以下示例數據時,會得到不同的結果:
var str1 = "{\"employees\": [" +
"{ \"firstName\":\"John\" , \"lastName\":\"Doe\" }, " +
"{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" }, " +
"{ \"firstName\":\"Peter\" , \"lastName\":\"Jones\" }" +
"]}";
//first try
public static JsonObject DeserializeJsonString(this string s) {
return JsonObject.Parse(s);
}
//second try
public static T DeserializeJson<T>(this string s) where T : class {
return JsonSerializer.DeserializeFromString<T>(s);
}
首先嘗試JsonObject.Parse()
:
再試一次JsonSerializer.DeserializeFromString<Dictionary<string, string>>()
:
為什么第二種方式會有不良數據?
編輯------------------------------------------------- ------
沒有問題了。
最新版本的SS已解決此問題。 現在它可以解析Dictionary <string, string>
了。
//Source code in ServiceStack.Text -> DeserializeDictionary.cs
//Line 89
//if type is JsonObject : Dictionary<string, string>
var mapKey = keyValue;
var mapValue = elementValue;
//Line 145
//if type is Dictionary<string, string>
var mapKey = Serializer.UnescapeString(keyValue);
var mapValue = Serializer.UnescapeString(elementValue);
這就是為什么:
var a = JsonSerializer.DeserializeFromString<Dictionary<string, string>>():
//returns <"key", "[{"> incorrect value
var b = JsonSerializer.DeserializeFromString<JsonObject>();
//returns <"key","[{...}]"> correct value
JsonObject繼承自Dictionary<string, string>
,但是它被賦予與普通Dictionary<string, string>
不同的含義Dictionary<string, string>
以進行特殊處理。 對我來說,“ a”和“ b”應該返回相同的答案,要么都起作用,要么都不起作用。 現在“ a”已損壞而“ b”有效,我個人認為這是一個邏輯錯誤。
我問自己為什么第二通電話完全被允許。
對於Dictionary<string, string>
我希望JSON字符串類似於{ "key1": "val1", ...}
但它是{ "key1": not a string, ...}
。 我期望它由於無效或意外的JSON格式而失敗(或返回null)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.