6

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;
        }
    }
3
  • Which json.net version do you use? Because the "Newtonsoft.Json" version="4.0.8" produces this: {"phrases":{"my-key1":"blah","my-key2":"blah2"}} using JsonConvert.SerializeObject(phrases); Commented May 18, 2012 at 15:10
  • @nemesv have updated my question Commented May 18, 2012 at 15:20
  • 1
    Am wondering if my problem is that it is still using the DataContractJsonSerializer instead of json.net Commented May 18, 2012 at 15:31

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.