zoukankan      html  css  js  c++  java
  • C#,json字符串转换成Json对象

    将JSON的请求参数转化为C#可序列化对象!

    JSON请求参数:

     "{"id":1,"name":"张三","dept":"销售部"}"

    或多组:

     Json = "[{"id":1,"name":"张三","dept":"销售部"},{"id":2"name":"李四","dept":"销售部"}]"

    首先要穷举可能用到的参数,或者每个请求单独写一个对象:

    public class RequestParameters
    {
        /// <summary>
        /// 应用范围:区域ID/部门ID/人员ID
        /// </summary>
        public string id { get; set; }
        /// <summary>
        /// 应用范围:姓名/区域名/部门名
        /// </summary>
        public string name { get; set; }
    }
    下面就是重点了,将字符串转化为实体对象

     public T ToJson<T>(string json)
        {
            System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
            DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(T));
            StreamWriter wr = new StreamWriter(stream2);
            wr.Write(json);
            wr.Flush();
            stream2.Position = 0;
            Object obj = ser2.ReadObject(stream2);
            T param = (T)obj;
            return param;
        }


    如果是返回一个List的话,就更简单了

     public List<T> ToJson<T>(string json)
        {
            System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
            DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(List<T>));
            StreamWriter wr = new StreamWriter(stream2);
            wr.Write(json);
            wr.Flush();
            stream2.Position = 0;
            Object obj = ser2.ReadObject(stream2);
            List<T> params = (List<T>)obj;
            return param;
        }

    就是这样,还有其他方法,比如使用正则表达式的:
    private static void TestRegex18()
    {
        string jstring = "{"112":1,"325":2,"109":3}";
        MatchCollection mc = Regex.Matches(jstring, @"""(?<key>[^""]+)"":(?<value>[^,}]+)");
        Dictionary<string, string> dict = new Dictionary<string, string>();
        foreach (Match m in mc)
        {
            if(dict.ContainsKey(m.Groups["key"].Value)) continue;//不能重复啊
            dict.Add(m.Groups["key"].Value, m.Groups["value"].Value);
        }
        //dict
    }


  • 相关阅读:
    MySQL Error--存储inode用完后报设备没有空间
    MySQL Binlog--基于ROW模式的binlog event大小限制
    MySQL Transaction--网络丢包导致长时间未提交事务
    java核心技术第四篇之JDBC第二篇
    java核心技术第三篇之JDBC第一篇
    java核心技术第二篇之数据库SQL语法
    JVM垃圾回收器原理及使用介绍
    JVM中优化指南
    MySQL常用工具、日志及读写分离
    java基础第十九篇之Xml
  • 原文地址:https://www.cnblogs.com/raphael5200/p/5114851.html
Copyright © 2011-2022 走看看