以下程序:

using System;
using Newtonsoft.Json;

namespace JsonPlayground
{
    public class Program
    {
        private struct Message
        {
            public string Value { get; }

            [JsonConstructor]
            public Message(string value)
            {
                if (value == null) throw new ArgumentNullException(nameof(value));

                Value = value;
            }
        }

        private class ObjectWithOptionalMessage
        {
            public Message? Message { get; }

            public ObjectWithOptionalMessage(Message? message)
            {
                Message = message;
            }
        }

        public static void Main(string[] args)
        {
            var objWithMessage = new ObjectWithOptionalMessage(new Message("Hello!"));

            var serializerSettings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Formatting = Formatting.Indented
            };

            Console.WriteLine(JsonConvert.SerializeObject(objWithMessage, serializerSettings));
        }
    }
}


给我以下输出:

{
  "Message": {
    "$type": "System.Nullable`1[[JsonPlayground.Program+Message, JsonPlayground]], System.Private.CoreLib",
    "Value": "Hello!"
  }
}


而且我想不出为什么要为明确声明的属性包含$type的原因。如果我声明Message属性不可为空,则不包括$type属性。

我究竟做错了什么?

最佳答案

David G的评论成功了,是将其表达为答案,并应用JsonPropertyAttribute,如下所示:

    private class ObjectWithOptionalMessage
    {
        [JsonProperty(TypeNameHandling = TypeNameHandling.None)]
        public Message? Message { get; }

        public ObjectWithOptionalMessage(Message? message)
        {
            Message = message;
        }
    }

确实为我解决了问题。

关于c# - 可为空的结构和TypeNameHandling.Auto的JSON.NET序列化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40108477/

10-10 21:56