C#后台接受前台JSON字符串装换成字典集合处理_技术学院_宜昌市隼壹珍商贸有限公司

您好,欢迎访问宜昌市隼壹珍商贸有限公司

400 890 5375
当前位置: 主页 > 新闻动态 > 技术学院

C#后台接受前台JSON字符串装换成字典集合处理

发布时间:2026-01-18  |  点击率:

一直以来,我们都是在服务端查询出结果生成JSON字符串,供前端调用,那么我们能否把从前端接受的JSON字符串转换成字典集合,让后台处理呢?

比如从前端接收:{'size':'10', 'weight':'10kg'}

在服务端转换成:[{size:"10"},{weight:"10kg"}]这样的字典集合

通过Newtonsoft的DeserializeObject<Dictionary<string, string>>方法可以把JSON字符串反序列化成字典集合。

假设有这样的一个Model(实体)

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class Product
{
  public string ProductDetails { get; set; }
  public Dictionary<string, string> ProductDetailList
  {
    get
    {
      if (string.IsNullOrWhiteSpace(ProductDetails))
      {
        return new Dictionary<string, string>();
      }
      try
      {
        var obj = JToken.Parse(ProductDetails);
      }
      catch (Exception)
      {
        throw new FormatException("ProductDetails不符合json格式.");
      }
      return JsonConvert.DeserializeObject<Dictionary<string, string>>(ProductDetails);
    }
  }
}

以上,通过JToken.Parse判断JSON字符串是否可以被转换,如果不行就抛异常。通过JsonConvert.DeserializeObject<Dictionary<string, string>>(ProductDetails)反序列化成字典集合。

public void Main(string[] args)
{
  var product = new Product();
  product.ProductDetails = "{'size':'10', 'weight':'10kg'}";

  foreach(var item in product.ProductDetailList)
  {
    Console.WriteLine(item.Key + " " + item.Value);
  }

  Console.Read();
}

创建Product实体,给product.ProductDetails属性赋值,程序会自动完成转换,这样我们就可以遍历product.ProductDetailList,将相应的值插入数据库,或做其他处理。

全国统一服务电话

400 890 5375

电子邮箱:879577@qq.com

公司地址:宜昌市西陵区黄河路5号三峡明珠10栋1051室

咨询微信

TEL:13680874598