Json.NET使用入门(三)【设置】

无论人生经历了什么都要明白,我们既不是最幸运的也不是最不幸的,因为我们所经历的有人早已体会,有人正在经历,有人即将面对,仅此而已。在人生低谷时谨记:我们并不是唯一面对这种处境的人,但却是唯一可以帮助自己真正走出来的人。只要向着阳光前行,办法总会比困难多。

各种相关辅助类:

public class AutofacContractResolver : DefaultContractResolver
     {
         private readonly IContainer _container;

         public AutofacContractResolver(IContainer container)
         {
             _container = container;
         }

         protected override JsonObjectContract CreateObjectContract(Type objectType)
         {
             JsonObjectContract contract = base.CreateObjectContract(objectType);

             // use Autofac to create types that have been registered with it
             if (_container.IsRegistered(objectType))
             {
                 contract.DefaultCreator = () => _container.Resolve(objectType);
             }

             return contract;
         }
     }

     public class TaskController
     {
         //private readonly ITaskRepository _repository;
         //private readonly ILogger _logger;

         //public TaskController(ITaskRepository repository,ILogger logger)
         //{
         // _repository = repository;
         // _logger = logger;
         //}

         //public ITaskRepository Repository
         //{
         // get { return _repository; }
         //}

         //public ILogger Logger
         //{
         // get { return _logger; }
         //}
     }
public class DynamicContractResolver : DefaultContractResolver
  {
      private readonly char _startingWithChar;

      public DynamicContractResolver(char startingWithChar)
      {
          _startingWithChar = startingWithChar;
      }

      protected override IList<JsonProperty> CreateProperties(Type type,MemberSerialization   memberSerialization)
      {
          IList<JsonProperty> properties = base.CreateProperties(type,memberSerialization);

          // only serializer properties that start with the specified character
          properties = properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();

          return properties;
      }
  }

  public class Person
  {
      public string FirstName { get; set; }
      public string LastName { get; set; }

      public string FullName
      {
          get { return FirstName + " " + LastName; }
      }
  }
public class KeysJsonConverter : JsonConverter
  {
      private readonly Type[] _types;

      public KeysJsonConverter(params Type[] types)
      {
          _types = types;
      }

      public override void WriteJson(JsonWriter writer,object value,JsonSerializer serializer)
      {
          JToken t = JToken.FromObject(value);

          if (t.Type != JTokenType.Object)
          {
              t.WriteTo(writer);
          }
          else
          {
              JObject o = (JObject)t;
              IList<string> propertyNames = o.Properties().Select(p => p.Name).ToList();

              o.AddFirst(new JProperty("Keys",new JArray(propertyNames)));

              o.WriteTo(writer);
          }
      }

      public override object ReadJson(JsonReader reader,Type objectType,object existingValue,JsonSerializer serializer)
      {
          throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
      }

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

      public override bool CanConvert(Type objectType)
      {
          return _types.Any(t => t == objectType);
      }
  }

  public class Employee
  {
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public IList<string> Roles { get; set; }
  }
public class KnownTypesBinder : SerializationBinder
   {
       public IList<Type> KnownTypes { get; set; }

       public override Type BindToType(string assemblyName,string typeName)
       {
           return KnownTypes.SingleOrDefault(t => t.Name == typeName);
       }

       public override void BindToName(Type serializedType,out string assemblyName,out    string typeName)
       {
           assemblyName = null;
           typeName = serializedType.Name;
       }
   }

   public class Car
   {
       public string Maker { get; set; }
       public string Model { get; set; }
   }
public class NLogTraceWriter : ITraceWriter
 {
     private static readonly Logger Logger = LogManager.GetLogger("NLogTraceWriter");

     public TraceLevel LevelFilter
     {
         // trace all messages. nlog can handle filtering
         get { return TraceLevel.Verbose; }
     }

     public void Trace(TraceLevel level,string message,Exception ex)
     {
         LogEventInfo logEvent = new LogEventInfo
         {
             Message = message,Level = GetLogLevel(level),Exception = ex
         };

         // log Json.NET message to NLog
         Logger.Log(logEvent);
     }

     private LogLevel GetLogLevel(TraceLevel level)
     {
         switch (level)
         {
             case TraceLevel.Error:
                 return LogLevel.Error;
             case TraceLevel.Warning:
                 return LogLevel.Warn;
             case TraceLevel.Info:
                 return LogLevel.Info;
             case TraceLevel.Off:
                 return LogLevel.Off;
             default:
                 return LogLevel.Trace;
         }
     }
 }
public class UserConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer,JsonSerializer serializer)
        {
            User user = (User) value;

            writer.WriteValue(user.UserName);
        }

        public override object ReadJson(JsonReader reader,JsonSerializer serializer)
        {
            User user = new User();
            user.UserName = (string) reader.Value;

            return user;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof (User);
        }
    }

    [JsonConverter(typeof (UserConverter))]
    public class User
    {
        public string UserName { get; set; }
    }

First.aspx内容:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="First.aspx.cs" Inherits="NewtonsoftDemo.First" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <table>

                    <tr>
                        <td>
                            <asp:Button ID="btnCustomJsonConverter" runat="server" Text="自定义 JsonConverter" OnClick="btnCustomJsonConverter_Click" />
                        </td>
                        <td>
                            <asp:Button ID="btnCustomIContractResolver" runat="server" Text="自定义 IContractResolver" OnClick="btnCustomIContractResolver_Click" style="height: 27px" /><br />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Button ID="btnCustomITraceWriter" runat="server" Text="自定义 ITraceWriter" OnClick="btnCustomITraceWriter_Click" />
                        </td>
                        <td>
                            <asp:Button ID="btnCustomSerializationBinder" runat="server" Text="自定义 SerializationBinder" OnClick="btnCustomSerializationBinder_Click" /><br />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Button ID="btnJsonConstructorAttribute" runat="server" Text="JsonConstructorAttribute" OnClick="btnJsonConstructorAttribute_Click" />
                        </td>
                        <td>
                            <asp:Button ID="btnJsonConverterAttributeOnclass" runat="server" Text="JsonConverterAttribute在类上" OnClick="btnJsonConverterAttributeOnclass_Click" /><br />
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <asp:Button ID="btnJsonConverterAttributeOnProperty" runat="server" Text="JsonConverterAttribute在属性上" OnClick="btnJsonConverterAttributeOnProperty_Click" />
                        </td>
                        <td>
                            <asp:Button ID="btnJsonObjectAttributeOptin" runat="server" Text="JsonObjectAttribute选择序列化" OnClick="btnJsonObjectAttributeOptin_Click" /><br />
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <asp:Button ID="btnJsonObjectAttributeForceOs" runat="server" Text="JsonObjectAttribute强行对象序列化" OnClick="btnJsonObjectAttributeForceOs_Click" />
                        </td>
                        <td>
                            <asp:Button ID="btnJsonPropertyAttributeName" runat="server" Text="JsonPropertyAttribute|name" OnClick="btnJsonPropertyAttributeName_Click" /><br />
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <asp:Button ID="btnJsonPropertyAttributeOrder" runat="server" Text="JsonPropertyAttribute|order" OnClick="btnJsonPropertyAttributeOrder_Click" />
                        </td>
                        <td>
                            <asp:Button ID="btnJsonPropertyAttributeRequired" runat="server" Text="JsonPropertyAttribute|required" OnClick="btnJsonPropertyAttributeRequired_Click" /><br />
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <asp:Button ID="btnJsonPropertyAttributeItemsSetting" runat="server" Text="JsonPropertyAttribute items 设置" OnClick="btnJsonPropertyAttributeItemsSetting_Click" />
                        </td>
                        <td>
                            <asp:Button ID="btnJsonPropertyAttributeProSetting" runat="server" Text="JsonPropertyAttribute property 设置" OnClick="btnJsonPropertyAttributeProSetting_Click" /><br />
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <asp:Button ID="btnJsonIgnoreAttribute" runat="server" Text="JsonIgnoreAttribute" OnClick="btnJsonIgnoreAttribute_Click" />
                        </td>
                        <td>
                            <asp:Button ID="btnErrorHandlingAttribute" runat="server" Text="ErrorHandlingAttribute" OnClick="btnErrorHandlingAttribute_Click" /><br />
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <asp:Button ID="btnDefaultValueAttribute" runat="server" Text="DefaultValueAttribute" OnClick="btnDefaultValueAttributeg_Click" />
                        </td>
                        <td>
                            <asp:Button ID="btnSerializationCallbackAttributes" runat="server" Text="序列化回调属性" OnClick="btnSerializationCallbackAttributes_Click" /><br />
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <asp:Button ID="btnDataContractAndDataMemberAttribute" runat="server" Text="DataContract和DataMember属性" OnClick="btnDataContractAndDataMemberAttributes_Click" />
                        </td>
                        <td>
                            <asp:Button ID="btnDeserializeWithDI" runat="server" Text="依赖注入反序列化" OnClick="btnDeserializeWithDI_Click" /><br />
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <asp:Button ID="btnSerializeWithDefaultSettings" runat="server" Text="用默认设置序列化" OnClick="btnSerializeWithDefaultSettings_Click" />
                        </td>
                        <td>
                            <asp:Button ID="btnSerializeImmutableCollection" runat="server" Text="序列化不可变集合" OnClick="btnSerializeImmutableCollection_Click" /><br />
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <asp:Button ID="btnDeserializeImmutableCollection" runat="server" Text="反序列化不可变集合" OnClick="btnDeserializeImmutableCollection_Click" />
                        </td>
                        <td>
                            <asp:Button ID="btnSerializeExtensionData" runat="server" Text="序列化扩展数据" OnClick="btnSerializeExtensionData_Click" />
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <asp:Button ID="btnDeserializeExtensionData" runat="server" Text="反序列化扩展数据" OnClick="btnDeserializeExtensionData_Click" />
                        </td>
                        <td>
                            <asp:Button ID="btnDeserializeDateFormatString" runat="server" Text="反序列化日期格式字符串" OnClick="btnDeserializeDateFormatString_Click" />
                        </td>
                    </tr>



                    <tr>
                        <td>
                            <asp:Button ID="btnSerializeDateFormatString" runat="server" Text="序列化日期格式字符串" OnClick="btnSerializeDateFormatString_Click" />
                        </td>
                        <td>

                        </td>
                    </tr>
                </table>
            </div>
        </form>
    </body>
</html>

First.aspx.cs代码:

public partial class First : System.Web.UI.Page
    {
        protected void Page_Load(object sender,EventArgs e)
        {
        }

        protected void btnCustomJsonConverter_Click(object sender,EventArgs e)
        {
            Employee employee = new Employee
            {
                FirstName = "James",LastName = "Newton-King",Roles = new List<string>
                {
                    "Admin"
                }
            };

            string json = JsonConvert.SerializeObject(employee,Formatting.Indented,new KeysJsonConverter(typeof (Employee)));

            Response.Write(json);

            Employee newEmployee = JsonConvert.DeserializeObject<Employee>(json,new KeysJsonConverter(typeof (Employee)));

            Response.Write(newEmployee.FirstName);
        }

        protected void btnCustomIContractResolver_Click(object sender,EventArgs e)
        {
            Person person = new Person
            {
                FirstName = "Dennis",LastName = "Deepwater-Diver"
            };

            string startingWithF = JsonConvert.SerializeObject(person,new JsonSerializerSettings {ContractResolver = new DynamicContractResolver('F')});

            Response.Write(startingWithF);

            string startingWithL = JsonConvert.SerializeObject(person,new JsonSerializerSettings {ContractResolver = new DynamicContractResolver('L')});

            Response.Write(startingWithL);
        }

        protected void btnCustomITraceWriter_Click(object sender,EventArgs e)
        {
            IList<string> countries = new List<string>
            {
                "New Zealand","Australia","Denmark","China"
            };

            string json = JsonConvert.SerializeObject(countries,new JsonSerializerSettings
            {
                TraceWriter = new NLogTraceWriter()
            });

            Response.Write(json);
        }

        protected void btnCustomSerializationBinder_Click(object sender,EventArgs e)
        {
            KnownTypesBinder knownTypesBinder = new KnownTypesBinder
            {
                KnownTypes = new List<Type> {typeof (Car)}
            };

            Car car = new Car
            {
                Maker = "Ford",Model = "Explorer"
            };

            string json = JsonConvert.SerializeObject(car,new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Objects,Binder = knownTypesBinder
            });

            Response.Write(json);
            // {
            // "$type": "Car",
            // "Maker": "Ford",
            // "Model": "Explorer"
            // }

            object newValue = JsonConvert.DeserializeObject(json,Binder = knownTypesBinder
            });

            Response.Write(newValue.GetType().Name);
            // Car
        }

        protected void btnJsonConstructorAttribute_Click(object sender,EventArgs e)
        {
            string json = @"{ ""UserName"": ""domain\\username"",""Enabled"": true }";

            User user = JsonConvert.DeserializeObject<User>(json);

            Response.Write(user.UserName);
            // domain\username
        }

        protected void btnJsonConverterAttributeOnclass_Click(object sender,EventArgs e)
        {
            User user = new User
            {
                UserName = @"domain\username"
            };

            string json = JsonConvert.SerializeObject(user,Formatting.Indented);

            Response.Write(json);
            // "domain\\username"
        }

        protected void btnJsonConverterAttributeOnProperty_Click(object sender,EventArgs e)
        {
            UserEntity user = new UserEntity
            {
                UserName = @"domain\username",Status = UserStatus.Deleted
            };

            string json = JsonConvert.SerializeObject(user,Formatting.Indented);

            Response.Write(json);
        }

        protected void btnJsonObjectAttributeOptin_Click(object sender,EventArgs e)
        {
            FileOp file = new FileOp
            {
                Id = Guid.NewGuid(),Name = "ImportantLegalDocuments.docx",Size = 50*1024
            };

            string json = JsonConvert.SerializeObject(file,Formatting.Indented);

            Response.Write(json);
        }

        protected void btnJsonObjectAttributeForceOs_Click(object sender,EventArgs e)
        {
            DirectoryEntity directory = new DirectoryEntity
            {
                Name = "My Documents",Files =
                {
                    "ImportantLegalDocuments.docx","WiseFinancalAdvice.xlsx"
                }
            };
            string json = JsonConvert.SerializeObject(directory,Formatting.Indented);
            Response.Write(json);
        }

        protected void btnJsonPropertyAttributeName_Click(object sender,EventArgs e)
        {
            Videogame starcraft = new Videogame
            {
                Name = "Starcraft",ReleaseDate = new DateTime(1998,1,1)
            };

            string json = JsonConvert.SerializeObject(starcraft,Formatting.Indented);

            Response.Write(json);
        }

        protected void btnJsonPropertyAttributeOrder_Click(object sender,EventArgs e)
        {
            AccountData account = new AccountData
            {
                FullName = "Aaron Account",EmailAddress = "aaron@example.com",Deleted = true,DeletedDate = new DateTime(2013,25),UpdatedDate = new DateTime(2013,CreatedDate = new DateTime(2010,10,1)
            };
            string json = JsonConvert.SerializeObject(account,Formatting.Indented);
            Response.Write(json);
        }

        protected void btnJsonPropertyAttributeRequired_Click(object sender,EventArgs e)
        {
            string json = @"{ 'Name': 'Starcraft III','ReleaseDate': null }";

            Videogame starcraft = JsonConvert.DeserializeObject<Videogame>(json);

            Response.Write(starcraft.Name);
            // Starcraft III

            Response.Write(starcraft.ReleaseDate);
            // null
        }

        protected void btnJsonPropertyAttributeItemsSetting_Click(object sender,EventArgs e)
        {
            EmployeeInfo manager = new EmployeeInfo
            {
                Name = "George-Michael"
            };
            EmployeeInfo worker = new EmployeeInfo
            {
                Name = "Maeby",Manager = manager
            };

            BusinessModel business = new BusinessModel
            {
                Name = "Acme Ltd.",Employees = new List<EmployeeInfo>
                {
                    manager,worker
                }
            };

            string json = JsonConvert.SerializeObject(business,Formatting.Indented);

            Response.Write(json);
        }

        protected void btnJsonPropertyAttributeProSetting_Click(object sender,EventArgs e)
        {
            Vessel vessel = new Vessel
            {
                Name = "Red October",Class = "Typhoon"
            };

            string json = JsonConvert.SerializeObject(vessel,Formatting.Indented);

            Response.Write(json);
        }

        protected void btnJsonIgnoreAttribute_Click(object sender,EventArgs e)
        {
            AccountEntity account = new AccountEntity
            {
                FullName = "Joe User",EmailAddress = "joe@example.com",PasswordHash = "VHdlZXQgJ1F1aWNrc2lsdmVyJyB0byBASmFtZXNOSw=="
            };

            string json = JsonConvert.SerializeObject(account);
            Response.Write(json);
        }

        protected void btnErrorHandlingAttribute_Click(object sender,EventArgs e)
        {
            EmployeeData person = new EmployeeData
            {
                Name = "George Michael Bluth",Age = 16,Roles = null,Title = "Mister Manager"
            };
            string json = JsonConvert.SerializeObject(person,Formatting.Indented);
            Response.Write(json);
        }

        protected void btnDefaultValueAttributeg_Click(object sender,EventArgs e)
        {
            Customer customer = new Customer();

            string jsonIncludeDefaultValues = JsonConvert.SerializeObject(customer,Formatting.Indented);
            Response.Write(jsonIncludeDefaultValues);

            string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(customer,new JsonSerializerSettings
                {
                    DefaultValueHandling = DefaultValueHandling.Ignore
                });

            Response.Write(jsonIgnoreDefaultValues);
        }

        protected void btnSerializationCallbackAttributes_Click(object sender,EventArgs e)
        {
            SerializationEventTestObject obj = new SerializationEventTestObject();

            Response.Write(obj.Member1);
            // 11
            Response.Write(obj.Member2);
            // Hello World!
            Response.Write(obj.Member3);
            // This is a nonserialized value
            Response.Write(obj.Member4);
            // null

            string json = JsonConvert.SerializeObject(obj,Formatting.Indented);
            // {
            // "Member1": 11,
            // "Member2": "This value went into the data file during serialization.",
            // "Member4": null
            // }

            Response.Write(obj.Member1);
            // 11
            Response.Write(obj.Member2);
            // This value was reset after serialization.
            Response.Write(obj.Member3);
            // This is a nonserialized value
            Response.Write(obj.Member4);
            // null

            obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(json);

            Response.Write(obj.Member1);
            // 11
            Response.Write(obj.Member2);
            // This value went into the data file during serialization.
            Response.Write(obj.Member3);
            // This value was set during deserialization
            Response.Write(obj.Member4);
            // This value was set after deserialization.
        }

        protected void btnDataContractAndDataMemberAttributes_Click(object sender,EventArgs e)
        {
            FileEntity file = new FileEntity
            {
                Id = Guid.NewGuid(),Formatting.Indented);

            Response.Write(json);
        }

        protected void btnDeserializeWithDI_Click(object sender,EventArgs e)
        {
        }

        protected void btnSerializeWithDefaultSettings_Click(object sender,EventArgs e)
        {
            // settings will automatically be used by JsonConvert.SerializeObject/DeserializeObject
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            //Staff s = new Staff
            //{
            // FirstName = "Eric",
            // LastName = "Example",
            // BirthDate = new DateTime(1980,4,20,DateTimeKind.Utc),
            // Department = "IT",
            // JobTitle = "Web Dude"
            //};

            //json = JsonConvert.SerializeObject(s);
        }

        protected void btnSerializeImmutableCollection_Click(object sender,EventArgs e)
        {
            //ImmutableList<string> l = ImmutableList.CreateRange(new List<string>
            //{
            // "One",
            // "II",
            // "3"
            //});

            //string json = JsonConvert.SerializeObject(l,Formatting.Indented);

        }

        protected void btnDeserializeImmutableCollection_Click(object sender,EventArgs e)
        {
            string json = @"[ 'One','II','3' ]";

            //ImmutableList<string> l = JsonConvert.DeserializeObject<ImmutableList<string>>(json);

            //foreach (string s in l)
            //{
            // Response.Write(s);
            //}

        }

        protected void btnSerializeExtensionData_Click(object sender,EventArgs e)
        {
            string json = @"{ 'HourlyRate': 150,'Hours': 40,'TaxRate': 0.125 }";

            //CustomerInvoice invoice = JsonConvert.DeserializeObject<CustomerInvoice>(json);

            //// increase tax to 15%
            //invoice.TaxRate = 0.15m;

            //string result = JsonConvert.SerializeObject(invoice);

        }

        protected void btnSerializeDateFormatString_Click(object sender,EventArgs e)
        {
            IList<DateTime> dateList = new List<DateTime>
            {
                new DateTime(2009,12,7,23,0,new DateTime(2010,9,2,DateTimeKind.Utc)
            };

            string json = JsonConvert.SerializeObject(dateList,new JsonSerializerSettings
            {
                DateFormatString = "d MMMM,yyyy",Formatting = Formatting.Indented
            });

            Response.Write(json);
        }

        protected void btnDeserializeDateFormatString_Click(object sender,EventArgs e)
        {
            string json = @"[ '7 December,2009','1 January,2010','10 February,2010' ]";

            IList<DateTime> dateList = JsonConvert.DeserializeObject<IList<DateTime>>(json,yyyy"
            });

            foreach (DateTime dateTime in dateList)
            {
                Response.Write(dateTime.ToLongDateString());
            }
        }

        protected void btnDeserializeExtensionData_Click(object sender,EventArgs e)
        {
            string json = @"{ 'DisplayName': 'John Smith','SAMAccountName': 'contoso\\johns' }";

            DirectoryAccount account = JsonConvert.DeserializeObject<DirectoryAccount>(json);

            Response.Write(account.DisplayName);
            // John Smith

            Response.Write(account.Domain);
            // contoso

            Response.Write(account.UserName);
            // johns
        }
    }

    #region JsonConstructorAttribute所需实体类

    public class User
    {
        [JsonConverter(typeof (UserConverter))]
        public string UserName { get;  set; }

        public bool Enabled { get; private set; }

        public User()
        {
        }

        [JsonConstructor]
        public User(string userName,bool enabled)
        {
            UserName = userName;
            Enabled = enabled;
        }
    }

    #endregion

    #region JsonConverterAttributeOnProperty所需实体类

    public enum UserStatus
    {
        NotConfirmed,Active,Deleted
    }

    public class UserEntity
    {
        public string UserName { get; set; }

        [JsonConverter(typeof (StringEnumConverter))]
        public UserStatus Status { get; set; }
    }

    #endregion

    #region JsonObjectAttributeOptin所需实体类

    [JsonObject(MemberSerialization.OptIn)]
    public class FileOp
    {
        // excluded from serialization
        // does not have JsonPropertyAttribute
        public Guid Id { get; set; }

        [JsonProperty]
        public string Name { get; set; }

        [JsonProperty]
        public int Size { get; set; }
    }

    #endregion

    #region JsonObjectAttribute Force Object Serialization所需实体类

    [JsonObject]
    public class DirectoryEntity : IEnumerable<string>
    {
        public string Name { get; set; }
        public IList<string> Files { get; set; }

        public DirectoryEntity()
        {
            Files = new List<string>();
        }

        public IEnumerator<string> GetEnumerator()
        {
            return Files.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    #endregion

    #region JsonPropertyAttribute name所需实体类

    public class Videogame
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("release_date")]
        public DateTime ReleaseDate { get; set; }
    }

    #endregion

    #region JsonPropertyAttribute order所需实体类

    public class AccountData
    {
        public string EmailAddress { get; set; }

        // appear last
        [JsonProperty(Order = 1)]
        public bool Deleted { get; set; }

        [JsonProperty(Order = 2)]
        public DateTime DeletedDate { get; set; }

        public DateTime CreatedDate { get; set; }
        public DateTime UpdatedDate { get; set; }

        // appear first
        [JsonProperty(Order = -2)]
        public string FullName { get; set; }
    }

    #endregion

    #region JsonPropertyAttribute name所需实体类

    public class PS4game
    {
        [JsonProperty(Required = Required.Always)]
        public string Name { get; set; }

        [JsonProperty(Required = Required.AllowNull)]
        public DateTime? ReleaseDate { get; set; }
    }

    #endregion

    #region JsonPropertyAttribute items所需实体类

    public class BusinessModel
    {
        public string Name { get; set; }

        [JsonProperty(ItemIsReference = true)]
        public IList<EmployeeInfo> Employees { get; set; }
    }

    public class EmployeeInfo
    {
        public string Name { get; set; }

        [JsonProperty(IsReference = true)]
        public EmployeeInfo Manager { get; set; }
    }

    #endregion

    #region JsonPropertyAttribute property 所需实体类

    public class Vessel
    {
        public string Name { get; set; }
        public string Class { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public DateTime? LaunchDate { get; set; }
    }

    #endregion

    #region JsonIgnoreAttribute 所需实体类

    public class AccountEntity
    {
        public string FullName { get; set; }
        public string EmailAddress { get; set; }

        [JsonIgnore]
        public string PasswordHash { get; set; }
    }

    #endregion

    #region ErrorHandlingAttribute所需实体类

    public class EmployeeData
    {
        private List<string> _roles;

        public string Name { get; set; }
        public int Age { get; set; }

        public List<string> Roles
        {
            get
            {
                if (_roles == null)
                {
                    throw new Exception("Roles not loaded!");
                }

                return _roles;
            }
            set { _roles = value; }
        }

        public string Title { get; set; }

        [OnError]
        internal void OnError(StreamingContext context,ErrorContext errorContext)
        {
            errorContext.Handled = true;
        }
    }

    #endregion

    #region DefaultValueAttribute所需实体类

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        [DefaultValue(" ")]
        public string FullName
        {
            get { return FirstName + " " + LastName; }
        }
    }

    #endregion

    #region SerializationEventTestObject所需实体类

    public class SerializationEventTestObject
    {
        // 2222
        // This member is serialized and deserialized with no change.
        public int Member1 { get; set; }

        // The value of this field is set and reset during and 
        // after serialization.
        public string Member2 { get; set; }

        // This field is not serialized. The OnDeserializedAttribute 
        // is used to set the member value after serialization.
        [JsonIgnore]
        public string Member3 { get; set; }

        // This field is set to null,but populated after deserialization.
        public string Member4 { get; set; }

        public SerializationEventTestObject()
        {
            Member1 = 11;
            Member2 = "Hello World!";
            Member3 = "This is a nonserialized value";
            Member4 = null;
        }

        [OnSerializing]
        internal void OnSerializingMethod(StreamingContext context)
        {
            Member2 = "This value went into the data file during serialization.";
        }

        [OnSerialized]
        internal void OnSerializedMethod(StreamingContext context)
        {
            Member2 = "This value was reset after serialization.";
        }

        [OnDeserializing]
        internal void OnDeserializingMethod(StreamingContext context)
        {
            Member3 = "This value was set during deserialization";
        }

        [OnDeserialized]
        internal void OnDeserializedMethod(StreamingContext context)
        {
            Member4 = "This value was set after deserialization.";
        }
    }

    #endregion

    #region DataContract and DataMember Attributes所需实体类

    [DataContract]
    public class FileEntity
    {
        // excluded from serialization
        // does not have DataMemberAttribute
        public Guid Id { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public int Size { get; set; }
    }

    #endregion

    #region Deserialize ExtensionData所需实体类

    public class DirectoryAccount
    {
        // normal deserialization
        public string DisplayName { get; set; }

        // these properties are set in OnDeserialized
        public string UserName { get; set; }
        public string Domain { get; set; }

        [JsonExtensionData] private IDictionary<string,JToken> _additionalData;

        [OnDeserialized]
        private void OnDeserialized(StreamingContext context)
        {
            // SAMAccountName is not deserialized to any property
            // and so it is added to the extension data dictionary
            string samAccountName = (string) _additionalData["SAMAccountName"];

            Domain = samAccountName.Split('\\')[0];
            UserName = samAccountName.Split('\\')[1];
        }

        public DirectoryAccount()
        {
            _additionalData = new Dictionary<string,JToken>();
        }
    }

    #endregion

结果如图:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


文章浏览阅读2.4k次。最近要优化cesium里的热力图效果,浏览了网络上的各种方法,发现大多是贴在影像上的。这么做好是好,但是会被自生添加的模型或者其他数据给遮盖。其次是网上的方法大多数是截取成一个矩形。不能自定义的截取自己所需要的。经过尝试,决定修改下cesium heatmap,让他达到我们需要的要求。首先先下载 cesium heatmap包。其中我们可以看到也是通过叠加entity达到添加canvas的方法绘制到地图上。我们先把这一段代码注释} else {} };
文章浏览阅读1.2w次,点赞3次,收藏19次。在 Python中读取 json文件也可以使用 sort ()函数,在这里我介绍一个简单的示例程序: (4)如果我们想将字符串转换为列表形式,只需要添加一个变量来存储需要转换的字符串即可。在上面的代码中,我们创建了一个名为` read`的对象,然后在文件的开头使用`./`关键字来命名该对象,并在文件中定义了一个名为` json`的变量,并在其中定义了一个名为` json`的字段。比如,我们可以使用 read方法读取 json文件中的内容,然后使用 send方法将其发送到 json文件中。_python怎么读取json文件
文章浏览阅读1.4k次。首字母缩略词 API 代表应用程序编程接口,它是一种设备,例如用于使用编程代码发送和检索数据的服务器。最常见的是,该技术用于从源检索数据并将其显示给软件应用程序及其用户。当您访问网页时,API 的工作方式与浏览器相同,信息请求会发送到服务器,如何在 Windows PC 中手动创建系统还原点服务器会做出响应。唯一的区别是服务器响应的数据类型,对于 API,数据是 JSON 类型。JSON 代表 JavaScript Object Notation,它是大多数软件语言中 API 的标准数据表示法。_api是什么 python
文章浏览阅读802次,点赞10次,收藏10次。解决一个JSON反序列化问题-空字符串变为空集合_cannot coerce empty string ("") to element of `java.util.arraylist
文章浏览阅读882次。Unity Json和Xml的序列化和反序列化_unity json反序列化存储换行
文章浏览阅读796次。reader.readAsText(data.file)中data.file的数据格式为。使用FileReader对象读取文件内容,最后将文件内容进行处理使用。_a-upload 同时支持文件和文件夹
文章浏览阅读775次,点赞19次,收藏10次。fastjson是由国内的阿里推出的一种json处理器,由java语言编写,无依赖,不需要引用额外的jar包,能直接运行在jdk环境中,它的解析速度是非常之快的,目前超过了所有json库。提示:以下是引用fastjson的方法,数据未涉及到私密信息。_解析器用fastjson还是jackson
文章浏览阅读940次。【Qt之JSON文件】QJsonDocument、QJsonObject、QJsonArray等类介绍及使用_使用什么方法检查qjsondocument是否为空
文章浏览阅读957次,点赞34次,收藏22次。主要内容原生 ajax重点重点JSON熟悉章节目标掌握原生 ajax掌握jQuery ajax掌握JSON第一节 ajax1. 什么是ajaxAJAX 全称为,表示异步的Java脚本和Xml文件,是一种异步刷新技术。2. 为什么要使用ajaxServlet进行网页的变更往往是通过请求转发或者是重定向来完成,这样的操作更新的是整个网页,如果我们只需要更新网页的局部内容,就需要使用到AJAX来处理了。因为只是更新局部内容,因此,Servlet。
文章浏览阅读1.4k次,点赞45次,收藏13次。主要介绍了JsonFormat与@DateTimeFormat注解实例解析,文中通过示例代码介绍的非常详细,对大家的学习 或者工作具有一定的参考学习价值,需要的朋友可以参考下 这篇文章主要介绍了从数据库获取时间传到前端进行展示的时候,我们有时候可能无法得到一个满意的时间格式的时间日期,在数据库中显 示的是正确的时间格式,获取出来却变成了时间戳,@JsonFormat注解很好的解决了这个问题,我们通过使用 @JsonFormat可以很好的解决:后台到前台时间格式保持一致的问题,
文章浏览阅读1k次。JsonDeserialize:json反序列化注解,作用于setter()方法,将json数据反序列化为java对象。可以理解为用在处理接收的数据上。_jsondeserialize
文章浏览阅读2.7k次。labelme标注的json文件是在数据标注时产生,不能直接应用于模型训练。各大目标检测训练平台或项目框架均有自己的数据格式要求,通常为voc、coco或yolo格式。由于yolov8项目比较火热,故此本博文详细介绍将json格式标注转化为yolo格式的过程及其代码。_labelme json 转 yolo
文章浏览阅读790次,点赞26次,收藏6次。GROUP_CONCAT_UNORDERED(): 与GROUP_CONCAT类似,但不保证结果的顺序。COUNT_DISTINCT_AND_ORDERED(): 计算指定列的不同值的数量,并保持结果的顺序。COUNT_ALL_DISTINCT(): 计算指定列的所有不同值的数量(包括NULL)。AVG_RANGE(): 计算指定列的最大值和最小值之间的差异的平均值。JSON_OBJECT(): 将结果集中的行转换为JSON对象。COUNT_DISTINCT(): 计算指定列的不同值的数量。_mysql json 聚合
文章浏览阅读1.2k次。ajax同步与异步,json-serve的安装与使用,node.js的下载_json-serve 与node版本
文章浏览阅读1.7k次。`.net core`提供了Json处理模块,在命名空间`System.Text.Json`中,下面通过顶级语句,对C#的Json功能进行讲解。_c# json
文章浏览阅读2.8k次。主要介绍了python对于json文件的读写操作内容_python读取json文件
文章浏览阅读770次。然而,有时候在处理包含中文字符的Json数据时会出现乱码的情况。本文将介绍一种解决Json中文乱码问题的常见方法,并提供相应的源代码和描述。而某些情况下,中文字符可能会被错误地编码或解码,导致乱码的出现。通过适当地控制编码和解码过程,我们可以有效地处理包含中文字符的Json数据,避免乱码的发生。通过控制编码和解码过程,我们可以确保Json数据中的中文字符能够正确地传输和解析。为了解决这个问题,我们可以使用C#的System.Text.Encoding类提供的方法进行编码和解码的控制。_c# json 中文编码
文章浏览阅读997次。【代码】【工具】XML和JSON互相转换。_xml 转json
文章浏览阅读1.1k次。json path 提取数据_jsonpath数组取值
文章浏览阅读3w次,点赞35次,收藏36次。本文主要介绍了pandas read_json时ValueError: Expected object or value的解决方案,希望能对学习python的同学们有所帮助。文章目录1. 问题描述2. 解决方案_valueerror: expected object or value