JSON使用ConstructorHanding反序列化非公共构造函数

来源:互联网 发布:网络教育作业答案 编辑:程序博客网 时间:2024/06/07 15:53

1.首先创建一个类,含有私有的构造函数.

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace JSONDemo{    public class Website    {        public string Url { get; set; }        private Website()        { }        public Website(Website website)        {            if (website == null)                throw new ArgumentNullException("website");            this.Url = website.Url;        }    }}


2.给类中的属性赋JSON格式的值,并反序列化

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using GongHuiNewtonsoft.Json;namespace JSONDemo{    class Program    {        static void Main(string[] args)        {            string json = @"{'Url':'http://blog.csdn.net/lovegonghui/article/details/50251873'}";            Website web = null;            try            {                web = JsonConvert.DeserializeObject<Website>(json);                       }            catch (Exception ex)            {                                Console.WriteLine(ex.Message);                //Console.WriteLine(web.Url);//未经处理的异常:  System.NullReferenceException: 未将对象引用设置到对象的实例。            }            Website website = JsonConvert.DeserializeObject<Website>(json, new JsonSerializerSettings            {                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor            });            Console.WriteLine(website.Url);        }    }}


3.运行的结果是

 

JSON源代码下载地址:http://download.csdn.net/detail/lovegonghui/9342751

 

0 0