我正在獲取一串 json 作為流并嘗試將其反序列化為 Dictionary<string, string> 問題在于它會阻塞數字,即使設定了序列化選項也是如此。如何使用 System.Text 做到這一點?
帶有 .NET 6 的 Program.cs:
using System;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
Console.WriteLine("Converting Json...");
var result = await DeserializeJson();
Console.WriteLine($"result: {result}");
async Task<Dictionary<string, string>> DeserializeJson()
{
var jsonText = "{\"number\": 709, \"message\": \"My message here\",\"bool\": true}";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
NumberHandling = JsonNumberHandling.WriteAsString
};
var fullResponse = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(stream, options);
return fullResponse;
}
導致的主要錯誤:
---> System.InvalidOperationException: Cannot get the value of a token type 'Number' as a string.
如果不是因為我設定了序列化選項的句柄數字屬性,這將是有意義的。這是已知的失敗還是這里出了什么問題?
uj5u.com熱心網友回復:
您的 json 不只包含字串。作為一種快速(但不是高性能的)修復,您可以嘗試將其反實作Dictionary<string, object>,然后將其轉換為Dictionary<string, string>:
async Task<Dictionary<string, string>> DeserializeJson()
{
var jsonText = "{\"number\": 709, \"message\": \"My message here\",\"bool\": true}";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
NumberHandling = JsonNumberHandling.WriteAsString ,
};
var fullResponse = await JsonSerializer.DeserializeAsync<Dictionary<string, Object>>(stream, options);
return fullResponse?.ToDictionary(pair => pair.Key, pair => pair.ToString());
}
或者手動決議檔案:
async Task<Dictionary<string, string>> DeserializeJson()
{
var jsonText = "{\"number\": 709, \"message\": \"My message here\",\"bool\": true}";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
var jsonDocument = JsonDocument.Parse(stream);
var dictionary = jsonDocument.RootElement
.EnumerateObject()
.ToDictionary(property => property.Name, property => property.Value.ToString());
return dictionary;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/376750.html
下一篇:使用泛型進行型別轉換
