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
}


原文地址:https://www.cnblogs.com/raphael5200/p/5114851.html