我得到一个json字符串作为流,并试图将其反序列化为字典
带.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.
json不仅仅包含字符串。作为一个快速(但不是性能)修复,您可以尝试反序列化到字典
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;
}