views:

12

answers:

0

the correct format for my keyvalue pairs is

{
    "Fields": 
       {
            "key1": "value1",
            "key2": "value2" 
        } 
}

But I cannot get this out of my object using the DataContractJsonSerializer, does anyone know how.

[DataContract] class Product {

     [DataMember]
     public Dictionary<string, string> KeyValues
     {
         get
         {
             Dictionary<string, string> d  = new Dictionary<string, string>();
             d.Add("key1", "value1");
             d.Add("key2", "value2");
             return d;
         }
     }
     [DataMember]
     public List<object> KeyValuesList
     {
         get
         {
             List<object> l = new List<object>();
             l.Add("key1" + ":" + "value1");
             l.Add("key2" + ":" + "value2");
             return l;
         }
     }
}

I've used a Dictionary but it returns

{
"Fields":[{"Key":"key1","Value":"value1"},{"Key":"key2","Value":"value2"}]
}

If I try to use a List and then combine the keys and values myself I can't seem to get around the requirement for double quotes

{
"Fields":["key1:value1","key2:value2"]}
}

This requires douvble quotes around both the key and value like so

{
"Fields":["key1":"value1","key2":"value2"]}
}

which I've also tried todo and failed, like so

 [DataMember]
         public List<object> KeyValuesList
         {
             get
             {
                 List<object> l = new List<object>();
                 l.Add("key1" + "\":\"" + "value1");
                 l.Add("key2" + "\":\"" + "value2");
                 return l;
             }
         }

results in additional unwanted \"

"KeyValuesList":["key1\":\"value1","key2\":\"value2"]}

and this is still not correct as it's an array which I do not want.

I've also tried the JavaScriptSerializer which comes closer to the mark but then has issues with more complex objects!

here's the object I'm playing with [DataContract] class Product {

     [DataMember]
     public Dictionary<string, string> KeyValues
     {
         get
         {
             Dictionary<string, string> d  = new Dictionary<string, string>();
             d.Add("key1", "value1");
             d.Add("key2", "value2");
             return d;
         }
     }
     [DataMember]
     public List<object> KeyValuesList
     {
         get
         {
             List<object> l = new List<object>();
             l.Add("key1" + ":" + "value1");
             l.Add("key2" + ":" + "value2");
             return l;
         }
     }
}