我正在尝试让 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"
}
我希望让它呈现如下:(href
和 type
没有引号)
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 - 序列化不带引号的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!