Convert the simple json string requested by the app into a dictionary

The JSON string can be deserialized into a dictionary collection through Newtonsoft's DeserializeObject<Dictionary<string, string>> method.

Suppose there is such a 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 does not conform to json format.");
            }
            return JsonConvert.DeserializeObject<Dictionary<string, string>>(ProductDetails);
        }
    }
}


Above, JToken.Parse is used to determine whether the JSON string can be converted, and if not, an exception is thrown. Deserialize into a dictionary collection by JsonConvert.DeserializeObject<Dictionary<string, string>>(ProductDetails).

finally,

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


Reprinted from: https://www.cnblogs.com/darrenji/p/5296221.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326551626&siteId=291194637