C#中服务端接受前端JSON字符串转换成字典集合

2018-06-17 21:19:41来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

 

我们是否可以把从前端接受的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();
}

 

遍历字典集合,可以把数据保存到数据库。

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:VS2005常用的快捷键分享

下一篇:Web基础知识