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
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值