雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C#教程

當(dāng)前位置:主頁(yè) > 軟件編程 > C#教程 >

C#后臺(tái)接受前臺(tái)JSON字符串裝換成字典集合處理

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C#教程|點(diǎn)擊:

一直以來,我們都是在服務(wù)端查詢出結(jié)果生成JSON字符串,供前端調(diào)用,那么我們能否把從前端接受的JSON字符串轉(zhuǎn)換成字典集合,讓后臺(tái)處理呢?

比如從前端接收:{'size':'10', 'weight':'10kg'}

在服務(wù)端轉(zhuǎn)換成:[{size:"10"},{weight:"10kg"}]這樣的字典集合

通過Newtonsoft的DeserializeObject<Dictionary<string, string>>方法可以把JSON字符串反序列化成字典集合。

假設(shè)有這樣的一個(gè)Model(實(shí)體)

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字符串是否可以被轉(zhuǎn)換,如果不行就拋異常。通過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();
}

創(chuàng)建Product實(shí)體,給product.ProductDetails屬性賦值,程序會(huì)自動(dòng)完成轉(zhuǎn)換,這樣我們就可以遍歷product.ProductDetailList,將相應(yīng)的值插入數(shù)據(jù)庫(kù),或做其他處理。

上一篇:C#如何遍歷Dictionary

欄    目:C#教程

下一篇:C# 如何獲取出錯(cuò)的錯(cuò)誤所在行數(shù)信息 &lt;font color=red&gt;原創(chuàng)&lt;/

本文標(biāo)題:C#后臺(tái)接受前臺(tái)JSON字符串裝換成字典集合處理

本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/6577.html

網(wǎng)頁(yè)制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語(yǔ)言數(shù)據(jù)庫(kù)服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有