.net Core 3.1 Newtonsoft.Json 转换字典<int,string>字符串的键 [英] .net Core 3.1 Newtonsoft.Json converts dictionary&lt;int,string&gt; key to string

查看:102
本文介绍了.net Core 3.1 Newtonsoft.Json 转换字典<int,string>字符串的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My custom object's one of properties is dictionary and I need to convert whole object to json string but JsonConvert changes dictionary key from Int to String which is what I don't want to happen.

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

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

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

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

推荐答案

我希望这可以让事情变得清晰一点,并希望它有所帮助!当我们调用 Json.SerializeObject 时,我们是在说获取我的对象并将其转换为字符串表示,以便我可以(例如)通过 HTTP 传输我的对象".

I'm hoping this might clear things up a little and hope it helps! When we call Json.SerializeObject we're saying "take my object and turn it into a string representation so that I can (for example) transmit my object over HTTP".

但是当你反序列化字符串表示时,一切都会回到原始类型.并不是说您可以避免转换",而是 Json 会自动进行转换,因此我们不必这样做.

But when you deserialize the string representation, everything goes back to the original types. It's not so much that you can "avoid conversion" but what happens is Json does the conversion automatically so we don't have to.

您可能会考虑尝试的一件事是创建一个像这样的自定义类:

One thing you might consider trying, that will give you very fine control over this process, is to make a custom class like so:

class CustomDictionary : Dictionary<int, string> { }

然后往返"序列化/反序列化将您带回到一个对象,其中 Key 是真正的 int 而只有 Value 是字符串:

Then the "round trip" serialize/deserialize puts you back to an object where the Key is truly an int and only the Value is a string:

    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);
    }

这篇关于.net Core 3.1 Newtonsoft.Json 转换字典<int,string>字符串的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆