Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make web api serialize dictionary with the key value as key using data attribute

I have a dictionary which I am serializing using the json.net serializer, and it is currently producing

{"phrases":[{"Key":"my-key1","Value":"blah"},{"Key":"my-key2","Value":"blah2"}]}

however I want it to output

{"phrases":["my-key1":"blah"},{"my-key2":"blah2"}]}

my model looks like

public class Phrases
{
    public Dictionary<string, string> phrases;
}

Is there a data attribute I can apply to the phrases model to cause this to happen?

I found the following but don't want to be returning a string Serialize into a key-value dictionary with Json.Net?

UPDATE:

I am extending the web api controller as follows, if I use JsonConvert.SerializeObject() I do get the correct serialization , however I would then have a string to return.

public class PhraseController : ApiController
    {
        private IApplicationModel applicationModel;

        public Phrases Get(string id)
        {
            var locale = new CultureInfo(id).LCID;
            var phrases = applicationModel.Phrases.Where(x => x.Locale = locale).ToDictionary(x => x.Name, y => y.Value);

            return new Phrases() { phrases = phrases };
        }

        public PhraseController(IApplicationModel applicationModel)
        {
            this.applicationModel = applicationModel;
        }
    }
like image 429
Tom Avatar asked May 18 '12 14:05

Tom


1 Answers

I managed to get it to work in the end.

Problem was that it was still using the DataContractJsonSerializer. I added a line removing the formatters before adding the JsonNetFormatter and it now serializes correctly.

GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.JsonFormatter);

GlobalConfiguration.Configuration.Formatters.Add(new JsonNetFormatter(null));

(I am using the beta release which still uses the DataContractJsonSerializer)

like image 177
Tom Avatar answered Nov 13 '22 17:11

Tom