2

I have a list of KeyPairValue wich I serialize in Json Object using JavaScriptSerializer. The output of this operation give me something like this :

[{"Key":"A","Value":"ValueA"},{"Key":"D","Value":"ValueD"}]

I'ld like to get rid of those "" around the property name so it could look like this :

[{ Key:"A", Value:"ValueA"},{ Key:"D", Value:"ValueD"}]

Is there a way to achieve this or if what i'm looking for is just not a Json serialization ?

1
  • I like JSON more than XML because it is easier to read and faster to write. But the "" for keys are so painful. Commented Feb 15, 2012 at 15:20

3 Answers 3

2

You can achieve it with Json.Net

StringWriter str = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(str);
writer.QuoteName = false; //<-- This is the trick
JsonSerializer jsonSer = new JsonSerializer();
jsonSer.Serialize(writer, new { ID = 1, Name = "Jack" });

string jsonstr = str.ToString();

Output is {ID:1,Name:"Jack"}

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

3 Comments

For the record: The generated output is what the poster asked for but is NOT valid Json (as is also noted in other answers). Many Json consumers will not accept/handle this string. You really should not even refer to it as Json since it isn't anymore.
@Eddy, OK. I name it from now on Myon (My Object Notation)
@LB Lol! Was not attempting to mock anyone but added the comment to warn any passers by that although this work it might bite you. I've answered the opposite question in the past here (why doesn't my .net webservice accept this 'json' string)
1

As I know it is a must requirement by JSON to embedd your keys in "". This is because JSON is actually a transport format for JavaScript objects and therefore it has some specifics.

Comments

0

The RFC specifies that a name is a string, and it also specifies that a string must be wrapped in quotation marks.

RFC 4627

It's worth noting the different types that values can be and that some of the types don't have to be wrapped in quotes. You can find this in the spec as well.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.