如何在Json.Net中设置QuoteName设置?

时间:2014-12-16 05:11:16

标签: json json.net settings

首先,我知道它不是有效的JSON格式,但它是我的客户Web服务设置,我需要将Json.Net JsonTextWriter的QuoteName设置为false,但我不是&# 39;不知道如何正确地做到这一点。这是我的尝试:

foreach (var c in a)
  {
    var jsonobjects = JsonConvert.SerializeObject(c, new JsonTextWriter
       {
           QuoteName = false
        }
      );
    //Some code that using serialized json object
   }

为了澄清我想要的东西。我需要没有引号的Json属性名称。类似的东西:{Property:" Value"}。

1 个答案:

答案 0 :(得分:2)

以下是一个例子:

课程:

public class Address
{
    public string Street { get; set; }

    public uint Number { get; set; }

    public string City { get; set; }

    public string ZipCode { get; set; }

    public string State { get; set; }

    public string Country { get; set; }
}

序列化逻辑:

var address = new Address
    {
        Street = "Fulton Street",
        Number = 100,
        City = "New York",
        ZipCode = "10038",
        State = "NY",
        Country = "USA"
    };

var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
using (var writer = new JsonTextWriter(stringWriter))
{
     writer.QuoteName = false;
     serializer.Serialize(writer, address);
}

var json = stringWriter.ToString();

Console.WriteLine(json);

<强>输出:

{
    Street: "Fulton Street",
    Number: 100,
    City: "New York",
    ZipCode: "10038",
    State: "NY",
    Country: "USA"
}

示例:

https://dotnetfiddle.net/zazT1T