如何序列化字典< string,string>而不用引号将值引起来? [英] How to Serialize a Dictionary<string,string> and not surround the value with quotes?

查看:54
本文介绍了如何序列化字典< string,string>而不用引号将值引起来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例模型:

public class Thing
{
[JsonProperty("foo")]    
public string Foo {get;set;}
[JsonProperty("bars")]  
public Dictionary<string,string> Bars {get;set;}
}

我希望输出看起来像这样:

i want the output to look like this:

{"foo":"Foo Value", "bars":{"key1":key1Value,"key2":key2Value}}

我希望Dictionary的值不带引号的原因是我可以通过jquery从客户端获取值:

The reason I want the values of the Dictionary to be without quotes is so I can pull the value from the client via jquery:

{"foo":"Foo Value", "bars":{"key1":$('#key1').val(),"key2":$('#key2').val()}}

使用Json.Net是否可能?

Is this possible using Json.Net?

推荐答案

这是我想到的实现:

public class DictionaryConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(Dictionary<string, string>);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var items = (Dictionary<string, string>)value;
           writer.WriteStartObject();
            foreach (var item in items)
            {

                writer.WritePropertyName(item.Key);
                writer.WriteRawValue(item.Value);

            }
            writer.WriteEndObject();
            writer.Flush();

        }
    }

这篇文章也有帮助.

这篇关于如何序列化字典&lt; string,string&gt;而不用引号将值引起来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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