Json.Net - 序列化的属性名称不带引号 [英] Json.Net - Serialize property name without quotes

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

问题描述

我试图让Json.Net以连载属性名称不带引号,并发现很难在谷歌找到的文档。我怎样才能做到这一点?



这是在一个大的JSON呈现一个非常小的一部分,所以我宁愿要么添加属性属性,或者重写连载方法。在类



目前,它呈现这样的:

 event_modal:
{
的href:file.html,
类型:满
}

和我希望得到它的渲染,如:(HREF&放大器;类型是不带引号)

 event_modal:
{
的href:file.html,
型:全
$} b $ b

从类:

 公共类ModalOptions 
{
公共对象的href {搞定;组; }
公共对象类型{搞定;组; }
}


解决方案

这是可能的,但< STRONG>我建议反对,因为它会产生无效的JSON作为马塞洛和Marc在他们的评论人士指出。



使用Json.NET库,你可以实现这一目标如下:

  [JSONObject的(MemberSerialization.OptIn)
公共类ModalOptions
$ { b $ b〔JsonProperty]
公共对象的href {搞定;组; }

[JsonProperty]
公共对象类型{搞定;组; }
}

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



例如:

  VAR选项=新ModalOptions {HREF =file.html,键入=全}; 
无功序列化=新JsonSerializer();
变种的StringWriter =新的StringWriter();
使用(VAR作家=新JsonTextWriter(StringWriter的))
{
writer.QuoteName = FALSE;
serializer.Serialize(作家,期权);
}
VAR JSON = stringWriter.ToString();

这将产生:

  {HREF:file.html,键入:满} 

如果您在JsonTextWriter实例的 QUOTENAME属性设置为false的对象名称将不不再被引用。


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

解决方案

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆