1

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?

DDiVita
  • 4,225
  • 5
  • 63
  • 117
  • Not sure I understand the question here, the JSON wouldn't be able to be deserialized without the quotes, or do you actually want it serialized as "$('#key1').val()"? – Paul Tyng Feb 14 '12 at 12:05
  • @PaulTyng, just like I have it above, I need the $('#key1').val() not to be in quotes when it is interpreted by the browser. I am expecting the JQuery selector to pull the value from an element on the page. If it remains in quotes, it is interpreted as a string and the JQuery selector is never run. This would be similar functionality if I were to call a JavaScript function in that section as well. – DDiVita Feb 14 '12 at 14:09
  • [This is similar to what I am looking for.][1] [1]: http://stackoverflow.com/questions/4547550/c-sharp-json-custom-serialization – DDiVita Feb 14 '12 at 16:02
  • Got it, sorry was slow on the response, you got the right answer though, this is the best use case for JSON.NET, any custom serialization stuff like this – Paul Tyng Feb 15 '12 at 17:01

1 Answers1

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.

Community
  • 1
  • 1
DDiVita
  • 4,225
  • 5
  • 63
  • 117