JSON.Net Seralize values don't have quotation marks

人走茶凉 提交于 2019-12-13 22:55:07

问题


The following code:

var json = JsonConvert.SerializeObject(fooObject,
                                                   new JsonSerializerSettings
                                                       {
                                                           NullValueHandling = NullValueHandling.Ignore,

                                                       });

Seralizes a json (string) object of:

{ "fooA":0, "fooB":0, "fooC":false, "fooD":false, "fooE":0, "fooF":0, }

The values are not in quotation marks, such as "fooA":"0". This is the behavior that I want.

Is there a way to enforce this behavior?


回答1:


In JSON format, numbers and booleans do not have quotes around them, while strings do (see JSON.org).

If you want quotes around all your primitives, you have a few options:

  1. Change the properties of the object you are serializing to be of type string.
  2. Put your values into a Dictionary<string, string> (or a DTO) and serialize that instead.
  3. Make a custom JsonConverter to do the conversion. This option has the advantage that it can apply globally so that you don't have to change all your classes.

The first two options are pretty self-explanatory. If you opted to go with a converter, the code might look something like this:

class PrimitiveToStringConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsPrimitive;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(value.ToString().ToLower());
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

To use it, simply pass an instance of the converter to the JsonConvert.SerializeObject method.

string json = JsonConvert.SerializeObject(foo, new PrimitiveToStringConverter());

Demo:

class Program
{
    static void Main(string[] args)
    {
        Foo foo = new Foo
        {
            Int = 6,
            Bool = true,
            Float = 3.14159
        };

        string json = JsonConvert.SerializeObject(foo, new PrimitiveToStringConverter());
        Console.WriteLine(json);
    }
}

class Foo
{
    public int Int { get; set; }
    public bool Bool { get; set; }
    public double Float { get; set; }
}

Output:

{"Int":"6","Bool":"true","Float":"3.14159"}


来源:https://stackoverflow.com/questions/21765588/json-net-seralize-values-dont-have-quotation-marks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!