将app请求的简单json串转化为字典

通过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();
}


转自:https://www.cnblogs.com/darrenji/p/5296221.html

猜你喜欢

转载自yh-fly.iteye.com/blog/2399906