这是this question(它的一个子集)绝对最简单的版本.

using System;
using System.Collections.Generic;
using System.Text.Json;


public class Program
{
    public class Subscription
    {
        public bool HasRead { get; set; } = true;
        public string TimeStamp { get; set; } = "";
    }



    public static void Main()
    {
        // this input format is a requirement. It cannot be changed.
        string json = @"
          {
            ""305FDF11-25E7-43DE-B09D-DFFC17C79599"": {
              ""hasRead"": true, // EDIT: Removed the double quotes around the boolean. That was not the core issue.
              ""Timestamp"": ""XXX""
            }
          }
        ";

        // I'm trying to find the correct deserialization type in C#
        var deser = JsonSerializer.Deserialize<KeyValuePair<string, Subscription>>(json,
            new JsonSerializerOptions(JsonSerializerDefaults.Web));

        // System.Text.Json.JsonException: 
        //'The JSON value could not be converted to 
        //System.Collections.Generic.KeyValuePair
    }
}

我不明白为什么它不能被反序列化.

注:我痴迷于KeyValuePair型,但可能与油田的shell 或其他明显的东西有关.

其他注意事项:当我将KeyValuePair<string, Subscription>更改为KeyValuePair<string, object>以使其更宽松时,它仍然失败.

推荐答案

首先,您的JSON不符合默认序列化KeyValuePair<string, Subscription>,我建议将类型切换为Dictionary<string, Subscription>.同样,默认的JSON反序列化程序无法反序列化您的JSON.我建议您使用Newtonsoft.Json

using Newtonsoft.Json;

string json = @"
          {
            ""305FDF11-25E7-43DE-B09D-DFFC17C79599"": {
              ""hasRead"": ""true"",
              ""Timestamp"": ""XXX""
            }
          }
        ";

var deserialized = JsonConvert.DeserializeObject<Dictionary<string, Subscription>>(json);
var subscription = deserialized["305FDF11-25E7-43DE-B09D-DFFC17C79599"];
Console.WriteLine($"Subscription timestamp is {subscription.TimeStamp}");

像这样,你会得到Subscription timestamp is XXX的输出.

Csharp相关问答推荐

为什么EF Core 6会针对null验证Count(*)?

WPF DataGrid中的三维数据

发布用于Linux Ubuntu的C#应用程序

最新的Mediatr和具有同步方法的处理程序Handle:并非所有代码路径都返回值"

如何将MongoDB序列化程序设置为内部对象属性

Blazor Web App WASM的两个独立项目令人困惑

有没有类似于扩展元素的合并元组的语法?

关于扩展文件类C#的矛盾

为什么C#/MSBuild会自发地为不同的项目使用不同的输出路径?

如何使用ODP.NET C#设置Oracle会话时间长度限制

RCL在毛伊岛应用程序和Blazor服务器应用程序.Net 8.0中使用页面

如何将默认区域性更改为fr-FR而不是en-US?

为什么Swashbakle/Swagger在参数中包含变量名?

为什么我的自定义Json.net转换器不工作?

使用本地公共PEM文件加密字符串,使用Azure KayVault中的私钥解密

HttpClient,上传文件时实现进度

与另一个对象位于同一位置的对象具有不同的变换位置

实例化列表时的集合表达式是什么?

分别切换用于读取和写入的EF核心日志(log)

在Word Open OpenXML c#上应用葡萄牙语字符Times New Roman时出错