• 解决WCF的service端无法使用泛型的问题


      思路是将其序列化(比较笨的方法……)

    1、引入Newtonsoft.json.dll

    2、服务端序列化:return JsonConvert.SerializeObject(result);

    3、客户端反序列化:List<T> list = JsonHelper.DeserializeJsonToList<T>(resultStr);

    4、封装的JsonHelper类,部分代码来自网络 ^_^

    using System.Collections.Generic;
    using Newtonsoft.Json;
    using System.IO;
    /// <summary>
    /// Json帮助类
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// 将对象序列化为JSON格式
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>json字符串</returns>
        public static string SerializeObject(object o)
        {
            string json = JsonConvert.SerializeObject(o);
            return json;
        }
    
        /// <summary>
        /// 解析JSON字符串生成对象实体
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param>
        /// <returns>对象实体</returns>
        public static T DeserializeJsonToObject<T>(string json) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(json);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
            T t = o as T;
            return t;
        }
    
        /// <summary>
        /// 解析JSON数组生成对象实体集合
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="json">json数组字符串(eg.[{"ID":"112","Name":"张三"}])</param>
        /// <returns>对象实体集合</returns>
        public static List<T> DeserializeJsonToList<T>(string json) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(json);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
            List<T> list = o as List<T>;
            return list;
        }
    
        /// <summary>
        /// 反序列化JSON到给定的匿名对象.
        /// </summary>
        /// <typeparam name="T">匿名对象类型</typeparam>
        /// <param name="json">json字符串</param>
        /// <param name="anonymousTypeObject">匿名对象</param>
        /// <returns>匿名对象</returns>
        public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
        {
            T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
            return t;
        }
    }
    View Code
  • 相关阅读:
    【bzoj1196】[HNOI2006]公路修建问题
    【bzoj1082】栅栏[SCOI2005]
    【bzoj1012】[JSOI2008]最大数maxnumber
    【bzoj2330】 [SCOI2011]糖果
    【bzoj1008】[HNOI2008]越狱
    【bzoj1002】 [FJOI2007]轮状病毒DP
    【bzoj1001】[BeiJing2006]狼抓兔子
    C++-POJ2234-Matches Game[Nim][SG函数]
    C++-POJ1067-取石子游戏
    lodash常用
  • 原文地址:https://www.cnblogs.com/lbhqq/p/5528353.html
Copyright © 2020-2023  润新知