v9.8.2018.0605   由DataReader直接映射实体列表,以支持netstandard的MySql和SQLite,且提升性能
大石头 编写于 2018-06-05 00:45:23
X
using System;
using NewLife.Data;
using NewLife.Net.Handlers;

namespace NewLife.Serialization
{
    /// <summary>Json编码解码器</summary>
    public class JsonCodec<T> : Handler
    {
        /// <summary>对象转Json</summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override Object Write(IHandlerContext context, Object message)
        {
            if (message is T entity) return new Packet(entity.ToJson().GetBytes());

            return message;
        }

        /// <summary>Json转对象</summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override Object Read(IHandlerContext context, Object message)
        {
            if (message is Packet pk) message = pk.ToStr();
            if (message is String str) return str.ToJsonEntity<T>();

            return message;
        }
    }
}