【问题标题】:.net Core 3.1 Newtonsoft.Json converts dictionary<int,string> key to string.net Core 3.1 Newtonsoft.Json 将 dictionary<int,string> 键转换为字符串
【发布时间】:2020-09-09 07:39:48
【问题描述】:

我的自定义对象的属性之一是字典,我需要将整个对象转换为 json 字符串,但 JsonConvert 将字典键从 Int 更改为 String,这是我不希望发生的。

var test = new Dictionary<int, string>
{
    [1] = "2"
};

var jsonDictionary = JsonConvert.SerializeObject(test, Formatting.None);

// output {"1":"2"}

我想要的输出应该是{ 1 : "2" }

【问题讨论】:

  • JSON 中不支持整数键。
  • 但是如果我在做 KeyValuPair 那么它可以工作吗?
  • @Haytam 任何解决方案如何解决?我的意思是我应该使用字符串键并在后端转换为 int 吗?
  • 对此没有解决方案,您的密钥必须是字符串才能使 JSON 有效且“可解析”。为什么你需要你的键是整数?
  • 解决方案是使用具有数字索引的数组(例如,[ , "2"]),或者处理字符串。真正的问题是您收到的输出是否可以反序列化为您期望的类型。换句话说,JsonConvert.DeserializeObject&lt;Dictionary&lt;int, string&gt;&gt;(jsonDictionary) 有效吗?

标签: c# json .net-core json.net


【解决方案1】:

我希望这可以让事情变得更清楚,希望对您有所帮助!当我们调用 Json.SerializeObject 时,我们说的是“获取我的对象并将其转换为字符串表示形式,以便我可以(例如)通过 HTTP 传输我的对象”。

但是当你反序列化字符串表示时,一切都会回到原始类型。与其说你可以“避免转换”,不如说是 Json 会自动进行转换,所以我们不必这样做。

你可能会考虑尝试的一件事,它可以让你很好地控制这个过程,那就是制作一个像这样的自定义类:

class CustomDictionary : Dictionary<int, string> { }

然后“往返”序列化/反序列化将您带回到 Key 是真正的 int 而只有 Value 是字符串的对象:

    static void Main(string[] args)
    {
        CustomDictionary myDict = new CustomDictionary();
        myDict[1] = "Two";
        string stringRepresentation = JsonConvert.SerializeObject(myDict);
        Console.WriteLine(stringRepresentation); // looks like {"1":"Two"}

        // Now it's back to normal Dictionary<int, string>
        CustomDictionary deserializedDict = JsonConvert.DeserializeObject<CustomDictionary>(stringRepresentation);
    }

【讨论】:

  • 我很高兴看到这么好的解释。 !谢谢!
  • 很高兴能帮上忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 2010-10-17
  • 2014-06-10
  • 1970-01-01
相关资源
最近更新 更多