序列含有字典这样一个对象,该字典键/值被呈现作为含对象的一部分 [英] Serializing an object containing a Dictionary such that the Dictionary keys/values are rendered as part of the containing object

查看:291
本文介绍了序列含有字典这样一个对象,该字典键/值被呈现作为含对象的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类如下:

public class Usage
{
    public string app { get; set; }

    public Dictionary<string, string> KVPs { get; set; }
}

当我使用此代码:

var json = new JavaScriptSerializer().Serialize(usage);



它给了我这个JSON:

it gives me this JSON:

{"app":"myapp", "KVPs":{"k1":"v1", "k2":"v2"}}

我想它返回这样的事情,而不是:

I'd like it to return something like this instead:

{"app":"myapp", "k1":"v1", "k2":"v2"}

有没有办法做到这一点?我目前使用的JavaScriptSerializer 。如果有一种方法可以做到这一点使用JSON.Net,我愿意切换到。

Is there a way to do this? I am currently using the JavaScriptSerializer. If there is a way to do this using JSON.Net, I would be willing to switch to that.

推荐答案

如果你想使用JSON.Net,你是​​愿意从词典<改变你的字典的类型;字符串,字符串> 词典<字符串对象> ,那么一个简单的方法来完成,这是在 [JsonExtensionData] 属性添加到您喜欢这本字典属性:

If you want to use JSON.Net and you're willing to change the type of your dictionary from Dictionary<string, string> to Dictionary<string, object>, then one easy way to accomplish this is to add the [JsonExtensionData] attribute to your dictionary property like this:

public class Usage
{
    public string app { get; set; }

    [JsonExtensionData]
    public Dictionary<string, object> KVPs { get; set; }
}



然后你可以序列化你的对象是这样的:

Then you can serialize your object like this:

string json = JsonConvert.SerializeObject(usage);

这会给你你想要的JSON:

This will give you the JSON you want:

{"app":"myapp","k1":"v1","k2":"v2"}

和奖金,你可以反序列化JSON回到你的很容易,如果需要使用类。在JSON不匹配的类成员的任何属性将被放置到 KVPs 词典。

And the bonus is, you can deserialize the JSON back to your Usage class just as easily if needed. Any properties in the JSON that do not match to members of the class will be placed into the KVPs dictionary.

Usage usage = JsonConvert.DeserializeObject<Usage>(json);

这篇关于序列含有字典这样一个对象,该字典键/值被呈现作为含对象的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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