Json.Net - 序列化不带引号的属性名称

Json.Net - Serialize property name without quotes(Json.Net - 序列化不带引号的属性名称)
本文介绍了Json.Net - 序列化不带引号的属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试让 Json.Net 序列化不带引号的属性名称,并且发现很难在 Google 上找到文档.我该怎么做?

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?

它在大型 Json 渲染的很小一部分中,所以我更喜欢添加一个属性属性,或者覆盖类上的序列化方法.

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.

目前,它呈现如下:

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

我希望让它呈现如下:(hreftype 没有引号)

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

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

来自班级:

public class ModalOptions
{
    public object href { get; set; }
    public object type { get; set; }
}

推荐答案

这是可能的,但 我不建议这样做,因为它会产生无效的 JSON,正如 Marcelo 和 Marc 在他们的评论中指出的那样.

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

使用 Json.NET 库,您可以按如下方式实现:

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

当序列化对象时,使用 JsonSerializer 类型而不是静态 JsonConvert 类型.

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

例如:

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();

这将产生:

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

如果您设置了 JsonTextWriter 实例的 QuoteName 属性为 false 将不再引用对象名称.

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

这篇关于Json.Net - 序列化不带引号的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Force JsonConvert.SerializeXmlNode to serialize node value as an Integer or a Boolean(强制 JsonConvert.SerializeXmlNode 将节点值序列化为整数或布尔值)
Using JSON to Serialize/Deserialize TimeSpan(使用 JSON 序列化/反序列化 TimeSpan)
Could not determine JSON object type for type quot;Classquot;(无法确定类型“Class的 JSON 对象类型.)
How to deserialize a JSONP response (preferably with JsonTextReader and not a string)?(如何反序列化 JSONP 响应(最好使用 JsonTextReader 而不是字符串)?)
how to de-serialize JSON data in which Timestamp it-self contains fields?(如何反序列化时间戳本身包含字段的JSON数据?)
JSON.Net custom contract serialization and Collections(JSON.Net 自定义合约序列化和集合)