Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

c# - Json.Net - Serialize property name without quotes

I'm trying to get Json.Net to serialise a property name without quote marks, and finding it difficult to locate documentation on Google. How can I do this?

It's in a very small part of a large Json render, so I'd prefer to either add a property attribute, or override the serialising method on the class.

Currently, the it renders like this:

"event_modal":
{
    "href":"file.html",
    "type":"full"
}

And I'm hoping to get it to render like: (href and type are without quotes)

"event_modal":
{
    href:"file.html",
    type:"full"
}

From the class:

public class ModalOptions
{
    public object href { get; set; }
    public object type { get; set; }
}
question from:https://stackoverflow.com/questions/7553516/json-net-serialize-property-name-without-quotes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's possible, but I advise against it as it would produce invalid JSON as Marcelo and Marc have pointed out in their comments.

Using the Json.NET library you can achieve this as follows:

[JsonObject(MemberSerialization.OptIn)]
public class ModalOptions
{
    [JsonProperty]
    public object href { get; set; }

    [JsonProperty]
    public object type { get; set; }
}

When serializing the object use the JsonSerializer type instead of the static JsonConvert type.

For example:

var options = new ModalOptions { href = "file.html", type = "full" };
var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
using (var writer = new JsonTextWriter(stringWriter))
{
    writer.QuoteName = false;
    serializer.Serialize(writer, options);            
}
var json = stringWriter.ToString();

This will produce:

{href:"file.html",type:"full"}

If you set the QuoteName property of the JsonTextWriter instance to false the object names will no longer be quoted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...