如何使用 System.Text.Json 将 json 字符串或流反序列化为 Dictionary<string,string>

How to deserialize a json string or stream to Dictionary<string,string> with System.Text.Json

我正在获取 json 的字符串作为流,并尝试将其反序列化为 Dictionary 问题是它会阻塞数字,即使序列化选项是放。如何用 System.Text 做到这一点?

Program.cs 与 .NET 6:

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 不仅仅包含字符串。作为一种快速(但不是高性能)修复,您可以尝试 deserealize 到 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;
}