Nicolas Boisvert
Nicolas Boisvert

Reputation: 1171

Custom Json serialization

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 ?

Upvotes: 2

Views: 845

Answers (3)

Jagd
Jagd

Reputation: 7306

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.

Upvotes: 0

L.B
L.B

Reputation: 116118

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"}

Upvotes: 2

brgerner
brgerner

Reputation: 4371

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.

Upvotes: 1

Related Questions