How to Serialize a Dictionary<string,string> and not surround the value with quotes?

回眸只為那壹抹淺笑 提交于 2019-12-08 05:30:12

问题


Example model:

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

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

Is this possible using Json.Net?


回答1:


This is my implementation I came up with:

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

        }
    }

This post helped too.



来源:https://stackoverflow.com/questions/9254820/how-to-serialize-a-dictionarystring-string-and-not-surround-the-value-with-quo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!