C # Background Accept foreground JSON string replace dictionary collection processing _c# tutorial

Source: Internet
Author: User

All along, we are in the server-side query results generated JSON string for front-end calls, then we can accept from the front-end JSON string into a dictionary collection, let the background processing?

such as receiving from the front: {' size ': ' Ten ', ' weight ': ' 10kg '}

Convert to: [{size: '},{weight: ' 10kg '}] such a collection of dictionaries

By Newtonsoft's deserializeobject<dictionary<string, the String>> method can deserialize the JSON string into a dictionary collection.

Suppose there is such a 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
        to 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, by Jtoken.parse to determine whether the JSON string can be converted, if not, throw the exception. by Jsonconvert.deserializeobject<dictionary<string, string>> (productdetails) is deserialized into a collection of dictionaries.

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

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

  Console.read ();
}

Create product entities, to product. ProductDetails property Assignment, the program automatically completes the transformation so that we can traverse product. Productdetaillist, insert the corresponding value into the database, or do other processing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.