JSON使用JsonConstructorAttribute,JsonConverterAttribute,JsonObjectAttribute

一、JSON使用JsonConstructorAttribute 在反序列化时创建对象(针对构造函数)

1.创建一个User对象.并添加JsonConstructor.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GongHuiNewtonsoft.Json;

namespace JSONDemo
{
    public class User
    {
        public string UserName { get; private set; }
        public bool Enabled { get; private set; }

        public User()
        { }

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


2.反序列化时创建User对象.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Serialization;
using GongHuiNewtonsoft.Json.Converters;

namespace JSONDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = @"{
                ""UserName"":""JSONDemo\\username"",
                ""Enabled"":true
            }";

            User user = JsonConvert.DeserializeObject<User>(json);
            Console.WriteLine(user.UserName);
            Console.WriteLine(user.Enabled);
        }
    }
}


3.运行的结果

 

二、JSON使用JsonConverterAttribute序列化对象中指定的成员(针对成员)

1.先创建一个UserConverter对象,继承JsonConverter,然后重写WriteJson与ReadJson方法,仅对User中成员UserName实现序列化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GongHuiNewtonsoft.Json;

namespace JSONDemo
{
    public class UserConverter:JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            User user = (User)value;
            writer.WriteValue(user.UserName);
        }

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

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

    }
}


2.创建一个User对象,并使用JsonConverter

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GongHuiNewtonsoft.Json;

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


3.序列化User对象

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Serialization;
using GongHuiNewtonsoft.Json.Converters;

namespace JSONDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            User user = new User
            {
                UserName = @"JSONDemo\username",
                Enabled=true
            };

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


4.运行结果,注意:Enabled设置了值,但是没有序列化

 

三、JSON使用JsonConverterAttribute序列化与反序列化(针对成员<引用类型>)

 1.先创建一个枚举

using System;

namespace JSONDemo
{
    public enum UserStatus
    {
        NotConfirmed,
        Active,
        Deleted
    }
}


2.再创建一个对象User,给其对象添加引用枚举的成员,并在其上指定JsonConverter类型,即UserStatus

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Converters;

namespace JSONDemo
{    
    public class User
    {
        public string UserName { get; set; }

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


3.序列化与反序列化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Serialization;
using GongHuiNewtonsoft.Json.Converters;

namespace JSONDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            User user = new User
            {
                UserName = @"JSONDemo\username",
                Status = UserStatus.Active
            };

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

            User user1 = JsonConvert.DeserializeObject<User>(json);
            Console.WriteLine(user1.UserName);
            Console.WriteLine(user1.Status);
        }
    }
}


4.运行的结果

四、JSON使用JsonObjectAttribute仅序列化指定JsonPropertyAttribute的属性

1.先创建一个File对象,然后添加JsonObject并指示仅属性序列化.即属性标记为System.Runtime.Serialization.DataMemberAttribute或者JsonProperty.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GongHuiNewtonsoft.Json;

namespace JSONDemo
{
    [JsonObject(MemberSerialization.OptIn)]
    public class File
    {
        public Guid Id { get; set; }

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

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


2.实例化File对象,然后序列化.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Serialization;
using GongHuiNewtonsoft.Json.Converters;

namespace JSONDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            File file = new File
            {
                Id = Guid.NewGuid(),
                Name = "JSONDemo.JsonObjectAttribute.OptIn",
                Size = 1024
            };

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


3.运行结果,注意:属性Id未被序列化.

 

五、JSON使用JsonObjectAttribute序列化类实现IEnumerable<T>作为JSON对象而不是JSON数组

1.创建一个Directory对象,继承IEnumerable<string>.添加一个构造函数,在其中实例化数组.然后实现GetEnumerator方法.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using GongHuiNewtonsoft.Json;

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

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

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

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


2.实例化Directory对象,然后给属性Files添加项,再序列化.注意:这里序列化是的IEnumerator<string>对象,而非数组.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Serialization;
using GongHuiNewtonsoft.Json.Converters;

namespace JSONDemo
{
    class Program
    {
        static void Main(string[] args)
        {            
            Directory dir = new Directory
            {
                Name = "GongHui's documents",
                Files =
                {
                    "JSONDemo.JsonObjectAttribute",
                    "JSONDemo.JsonObjectAttribute.IEnumerable<T>"
                }
            };

            string json = JsonConvert.SerializeObject(dir, Formatting.Indented);
            Console.WriteLine(json);
        }
    }
}


3.运行的结果

 

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

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值