首页 > 解决方案 > C# MVC 无法反序列化元组

问题描述

我有一个看起来像这样的 Json 模型

private class SearchMetadataJson
{
      public string entertain { get; set; }
      public string master { get; set; }
      public string memail { get; set; }
      public string key { get; set; }
      public (int, string)[] mood { get; set; }
      public int? soundnumber { get; set; }
      public int? ftv { get; set; }
      public int? com { get; set; }
      public (int, string)[] sims { get; set; }
      public (int, string)[] keysecond { get; set; }
      public string popt { get; set; }
      public (string, string) syncs { get; set; }
 }

我尝试像这样反序列化对象

var CommentObj = JsonSerializer.Deserialize<SearchMetadataJson>(CommentAsString);

我试图反序列化的数据(又名“CommentAsString”)看起来像这样

"{\"entertain\":\"PEG\",\"master\":\"Phos Ent Group\",\"memail\":\"example@example.com\",\"key\":\"Db\",\"mood\":{\"1\":\"TypeA\",\"4\":\"TypeB\",\"5\":\"TypeC\"},\"soundnumber\":\"5\",\"ftv\":\"4\",\"com\":\"3\",\"sims\":{\"1\":\"Band1\",\"2\":\"Band2\"},\"keysecond\":{\"1\":\"KeyWord1\",\"2\":\"KeyWord2\",\"3\":\"KeyWord3\"},\"syncs\":{\"Other pubber\":\"example2@example.com\"}}"

但我不断收到此错误
在此处输入图像描述

有谁看到问题是什么?

更新
中的整数CommentAsString是变量,每次调用函数时都会有所不同,因此我无法创建具有特定整数键值的 Json 对象。

标签: c#asp.net-mvctuplesjson-deserialization

解决方案


我们来看看实际的格式化数据结构

{
   "entertain":"PEG",
   "master":"Phos Ent Group",
   "memail":"example@example.com",
   "key":"Db",
   "mood":{
      "1":"TypeA",
      "4":"TypeB",
      "5":"TypeC"
   },
   "soundnumber":"5",
   "ftv":"4",
   "com":"3",
   "sims":{
      "1":"Band1",
      "2":"Band2"
   },
   "keysecond":{
      "1":"KeyWord1",
      "2":"KeyWord2",
      "3":"KeyWord3"
   },
   "syncs":{
      "Other pubber":"example2@example.com"
   }
}

将这些转换为元组数组是不寻常的。你似乎拥有的是字典的

例子

private class SearchMetadataJson
{
      public string entertain { get; set; }
      public string master { get; set; }
      public string memail { get; set; }
      public string key { get; set; }
      public Dictionary<int,string> mood { get; set; }
      public int? soundnumber { get; set; }
      public int? ftv { get; set; }
      public int? com { get; set; }
      public Dictionary<int,string> sims { get; set; }
      public Dictionary<int,string> keysecond { get; set; }
      public string popt { get; set; }
     // public (string, string) syncs { get; set; }
 }

最后一个属性是对象还是另一个字典还有待商榷。

"syncs":{
   "Other pubber":"example2@example.com"
}

不过,我会把它留给你。


推荐阅读