The C background accepts the processing of replacing the foreground JSON string with the dictionary set

  • 2021-09-16 07:44:01
  • OfStack

Since 1, we have been querying the results on the server to generate JSON strings for the front-end call, so can we convert the JSON strings accepted from the front-end into dictionary sets for background processing?

For example, receive from the front end: {'size': '10', 'weight': '10kg'}

Convert to: [{size: "10"}, {weight: "10kg"}] on the server side

DeserializeObject via Newtonsoft < Dictionary < string, string > > Method can deserialize an JSON string into a dictionary collection.

Suppose there is such an Model (entity)


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 Not conforming json Format .");
      }
      return JsonConvert.DeserializeObject<Dictionary<string, string>>(ProductDetails);
    }
  }
}

Above, judge whether JSON string can be converted by JToken. Parse, and throw an exception if not. Through JsonConvert. DeserializeObject < Dictionary < string, string > > (ProductDetails) is deserialized into a dictionary set.


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

Create an Product entity, assign a value to the product. ProductDetails attribute, and the program will automatically complete the transformation, so that we can traverse product. ProductDetailList, insert the corresponding value into the database, or do other processing.


Related articles: