点晴MIS内部交流论坛 加入收藏
新手上路
论坛搜索
 您的位置:点晴MIS系统问题答疑『 技术文档交流 』浏览当前帖子  
登 陆注 册论坛帮助  

  网站搜索
  搜索范围: 搜索方式: 关键词(可用空格分开)  

  作者及文章信息: 本文热度:541 % 
admin

积分:74803
等级:网站管理员
文数:13698
注册:2004-7-20

 信息   留言   主页   编辑   引用    

楼 顶 

 C#使用Newtonsoft.Json读写json、读写Base64图像


废话不多说,直接上最精炼的代码,假设json串如下:
{
    "key1": "val1",
    "key2": {
        "obj1": ["a", "b", "c"],
        "obj2": 12.3
    }
}

解析json串:
JObject jsonObj = (JObject)JsonConvert.DeserializeObject("{'key1':'val1','key2':{'obj1':['a','b','c'],'obj2':12.3}}");
string val = (string)jsonObj["key1"];
JArray arry = (JArray)jsonObj["key2"]["obj1"];
string valb = (string)arry[1];
double val2 = (double)jsonObj["key2"]["obj2"];

创建json串:
JObject obj= new JObject();
obj["key1"] = "val1";
JObject objKey2 = new JObject();
JArray  arry1 = new JArray() { "a","b","c"};
objKey2["obj1"] = arry1;
objKey2["obj2"] = 12.3;
obj["key2"] = objKey2;
string json = obj.ToString();

下面是一个更复杂的例子,假设json串如下:
{
  "txtRectangWidth": "100",
  "txtRectangHeight": "50",
  "txtRectangPrintWidth": "25",
  "txtRectangPrintHeight": "12.5",
  "txtLabelWidth": "40",
  "txtLabelHeight": "30",
  "txtLabelMoveUp": "0",
  "txtLabelMoveLeft": "0",
  "cBoxPrintDirect": "0",
  "cBoxPrinterName": "",
  "chkShowPrintingPreview": "0",
  "chkLogoAble": "0",
  "chkTextAble": "0",
  "chkBarcodeAble": "0",
  "chkQrcodeAble": "0",
  "chkLineAble": "0",
  "chkRectangleAble": "0",
  "LogoAble": [
    {
      "txtLogoTop": "0",
      "txtLogoLeft": "0",
      "txtLogoWidth": "30",
      "txtLogoHeight": "12",
      "txtLogoPath": "",
      "txtLogoUrl": ""
    }
  ],
  "TextAble": [
    {
      "txtTextTop": "0",
      "txtTextLeft": "0",
      "txtTextWidth": "0",
      "cBoxTextFontSize": "9",
      "cBoxTextFontFamily": "微软雅黑",
      "txtTextContent": "代码:DSC103231\r\n名称:标签打印机\r\n型号:DH3210\r\n日期:2022-1-1\r\n状态:合格\r\n仓位:A312",
      "cBoxTextType": "文字",
      "radioTextScale": "1",
      "radioTextDirectWrap": "0",
      "chkTextBold": "0",
      "chkTextDirect": "0"
    }
  ],
  "BarcodeAble": [
    {
      "cBoxBarcodeType": "CODE128",
      "txtBarcodeWidth": "30",
      "txtBarcodeHeight": "10",
      "txtBarcodeTop": "0",
      "txtBarcodeLeft": "0",
      "txtBarCode": "P0123456789"
    }
  ],
  "QrcodeAble": [
    {
      "txtQrcodeWidth": "15",
      "txtQrcodeTop": "14",
      "txtQrcodeLeft": "24",
      "txtQRCode": "DEMO:www.clicksun.cn",
      "txtQrcodeAdjustNum": "1"
    }
  ],
  "LineAble": [
    {
      "cBoxLineDirect": "横线",
      "txtLineTop": "0",
      "txtLineLeft": "0",
      "txtLineLength": "15",
      "txtLineWidth": "1",
      "cBoxLineStyle": "实线"
    }
  ],
  "RectangleAble": [
    {
      "txtRectangleTop": "0",
      "txtRectangleLeft": "0",
      "txtRectangleWidth": "36",
      "txtRectangleHeight": "26",
      "txtRectangleBorderWidth": "1",
      "cBoxRectangleStyle": "实线"
    }
  ]
}

解析json串:
try
{
    string tmpPath = "";
    OpenFileDialog fileDialog = new OpenFileDialog();
    fileDialog.Multiselect = false;
    fileDialog.Title = "请选择json文件路径";
    fileDialog.Filter = "json文件|*.json";
    if (fileDialog.ShowDialog() == DialogResult.OK)
    {
        string[] DragFilePaths = fileDialog.FileNames;
        foreach (string DragFilePath in DragFilePaths)
        {
            FileInfo NewAddFile = new FileInfo(DragFilePath);
            tmpPath = NewAddFile.FullName;
            break;
        }
    }
    if (tmpPath == "") { return; }
    //读入外部json文件
    StreamReader reader = File.OpenText(tmpPath);
    JsonTextReader jsonTextReader = new JsonTextReader(reader);
    JObject jsonObject = (JObject)JToken.Readfrom(jsonTextReader);
    //JObject jsonObject = (JObject)JToken.Parse(jsonText);  //直接从string加载
    txtRectangWidth.Text = jsonObject["txtRectangWidth"].ToString();
    txtRectangHeight.Text = jsonObject["txtRectangHeight"].ToString();
    txtRectangPrintWidth.Text = jsonObject["txtRectangPrintWidth"].ToString();
    txtRectangPrintHeight.Text = jsonObject["txtRectangPrintHeight"].ToString();
    txtLabelWidth.Text = jsonObject["txtLabelWidth"].ToString();
    txtLabelHeight.Text = jsonObject["txtLabelHeight"].ToString();
    txtLabelMoveUp.Text = jsonObject["txtLabelMoveUp"].ToString();
    txtLabelMoveLeft.Text = jsonObject["txtLabelMoveLeft"].ToString();
    cBoxPrintDirect.Text = jsonObject["cBoxPrintDirect"].ToString();
    cBoxPrinterName.Text = jsonObject["cBoxPrinterName"].ToString();
    if (jsonObject["cBoxPrintDirect"].ToString() == "1") { chkPrintTestRectangle.Checked = true; } else { chkPrintTestRectangle.Checked = false; }
    if (jsonObject["chkShowPrintingPreview"].ToString() == "1") { chkShowPrintingPreview.Checked = true; } else { chkShowPrintingPreview.Checked = false; }
    if (jsonObject["chkLogoAble"].ToString() == "1") { chkLogoAble.Checked = true; } else { chkLogoAble.Checked = false; }
    if (jsonObject["chkTextAble"].ToString() == "1") { chkTextAble.Checked = true; } else { chkTextAble.Checked = false; }
    if (jsonObject["chkBarcodeAble"].ToString() == "1") { chkBarcodeAble.Checked = true; } else { chkBarcodeAble.Checked = false; }
    if (jsonObject["chkQrcodeAble"].ToString() == "1") { chkQrcodeAble.Checked = true; } else { chkQrcodeAble.Checked = false; }
    if (jsonObject["chkLineAble"].ToString() == "1") { chkLineAble.Checked = true; } else { chkLineAble.Checked = false; }
    if (jsonObject["chkRectangleAble"].ToString() == "1") { chkRectangleAble.Checked = true; } else { chkRectangleAble.Checked = false; }

    //读取LogoAble
    txtLogoTop.Text = jsonObject["LogoAble"][0]["txtLogoTop"].ToString();
    txtLogoLeft.Text = jsonObject["LogoAble"][0]["txtLogoLeft"].ToString();
    txtLogoWidth.Text = jsonObject["LogoAble"][0]["txtLogoWidth"].ToString();
    txtLogoHeight.Text = jsonObject["LogoAble"][0]["txtLogoHeight"].ToString();
    txtLogoPath.Text = jsonObject["LogoAble"][0]["txtLogoPath"].ToString();
    txtLogoUrl.Text = jsonObject["LogoAble"][0]["txtLogoUrl"].ToString();

    //读取TextAble
    txtTextTop.Text = jsonObject["TextAble"][0]["txtTextTop"].ToString();
    txtTextLeft.Text = jsonObject["TextAble"][0]["txtTextLeft"].ToString();
    txtTextWidth.Text = jsonObject["TextAble"][0]["txtTextWidth"].ToString();
    cBoxTextFontSize.Text = jsonObject["TextAble"][0]["cBoxTextFontSize"].ToString();
    cBoxTextFontFamily.Text = jsonObject["TextAble"][0]["cBoxTextFontFamily"].ToString();
    txtTextContent.Text = jsonObject["TextAble"][0]["txtTextContent"].ToString();
    cBoxTextType.Text = jsonObject["TextAble"][0]["cBoxTextType"].ToString();
    if (jsonObject["TextAble"][0]["radioTextScale"].ToString() == "1") { radioTextScale.Checked = true; } else { radioTextScale.Checked = false; }
    if (jsonObject["TextAble"][0]["radioTextDirectWrap"].ToString() == "1") { radioTextDirectWrap.Checked = true; } else { radioTextDirectWrap.Checked = false; }
    if (jsonObject["TextAble"][0]["chkTextBold"].ToString() == "1") { chkTextBold.Checked = true; } else { chkTextBold.Checked = false; }
    if (jsonObject["TextAble"][0]["chkTextDirect"].ToString() == "1") { chkTextDirect.Checked = true; } else { chkTextDirect.Checked = false; }

    //读取BarcodeAble
    cBoxBarcodeType.Text = jsonObject["BarcodeAble"][0]["cBoxBarcodeType"].ToString();
    txtBarcodeWidth.Text = jsonObject["BarcodeAble"][0]["txtBarcodeWidth"].ToString();
    txtBarcodeHeight.Text = jsonObject["BarcodeAble"][0]["txtBarcodeHeight"].ToString();
    txtBarcodeTop.Text = jsonObject["BarcodeAble"][0]["txtBarcodeTop"].ToString();
    txtBarcodeLeft.Text = jsonObject["BarcodeAble"][0]["txtBarcodeLeft"].ToString();
    txtBarCode.Text = jsonObject["BarcodeAble"][0]["txtBarCode"].ToString();

    //读取QrcodeAble
    txtQrcodeWidth.Text = jsonObject["QrcodeAble"][0]["txtQrcodeWidth"].ToString();
    txtQrcodeTop.Text = jsonObject["QrcodeAble"][0]["txtQrcodeTop"].ToString();
    txtQrcodeLeft.Text = jsonObject["QrcodeAble"][0]["txtQrcodeLeft"].ToString();
    txtQRCode.Text = jsonObject["QrcodeAble"][0]["txtQRCode"].ToString();
    txtQrcodeAdjustNum.Text = jsonObject["QrcodeAble"][0]["txtQrcodeAdjustNum"].ToString();

    //读取LineAble
    cBoxLineDirect.Text = jsonObject["LineAble"][0]["cBoxLineDirect"].ToString();
    txtLineTop.Text = jsonObject["LineAble"][0]["txtLineTop"].ToString();
    txtLineLeft.Text = jsonObject["LineAble"][0]["txtLineLeft"].ToString();
    txtLineLength.Text = jsonObject["LineAble"][0]["txtLineLength"].ToString();
    txtLineWidth.Text = jsonObject["LineAble"][0]["txtLineWidth"].ToString();
    cBoxLineStyle.Text = jsonObject["LineAble"][0]["cBoxLineStyle"].ToString();

    //读取RectangleAble
    txtRectangleTop.Text = jsonObject["RectangleAble"][0]["txtRectangleTop"].ToString();
    txtRectangleLeft.Text = jsonObject["RectangleAble"][0]["txtRectangleLeft"].ToString();
    txtRectangleWidth.Text = jsonObject["RectangleAble"][0]["txtRectangleWidth"].ToString();
    txtRectangleHeight.Text = jsonObject["RectangleAble"][0]["txtRectangleHeight"].ToString();
    txtRectangleBorderWidth.Text = jsonObject["RectangleAble"][0]["txtRectangleBorderWidth"].ToString();
    cBoxRectangleStyle.Text = jsonObject["RectangleAble"][0]["cBoxRectangleStyle"].ToString();

    reader.Close();
}
catch (Exception ex)
{
    MessageBox.Show("保存失败,错误原因:\r\n" + ex.Message, "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}

创建json串并保存到指定文件:
try
{
    string tmpPath = SaveFilePathName("","json文件|*.json","将本模板另存为json文件");
    if (tmpPath=="") { return; }
    JObject jsonObject = new JObject();
    jsonObject["txtRectangWidth"] = txtRectangWidth.Text;
    jsonObject["txtRectangHeight"] = txtRectangHeight.Text;
    jsonObject["txtRectangPrintWidth"] = txtRectangPrintWidth.Text;
    jsonObject["txtRectangPrintHeight"] = txtRectangPrintHeight.Text;
    jsonObject["txtLabelWidth"] = txtLabelWidth.Text;
    jsonObject["txtLabelHeight"] = txtLabelHeight.Text;
    jsonObject["txtLabelMoveUp"] = txtLabelMoveUp.Text;
    jsonObject["txtLabelMoveLeft"] = txtLabelMoveLeft.Text;
    jsonObject["cBoxPrintDirect"] = cBoxPrintDirect.Text;
    jsonObject["cBoxPrinterName"] = cBoxPrinterName.Text;
    if (chkPrintTestRectangle.Checked == true) { jsonObject["cBoxPrintDirect"] = "1"; } else { jsonObject["cBoxPrintDirect"] = "0"; }
    if (chkShowPrintingPreview.Checked == true) { jsonObject["chkShowPrintingPreview"] = "1"; } else { jsonObject["chkShowPrintingPreview"] = "0"; }
    if (chkLogoAble.Checked == true) { jsonObject["chkLogoAble"] = "1"; } else { jsonObject["chkLogoAble"] = "0"; }
    if (chkTextAble.Checked == true) { jsonObject["chkTextAble"] = "1"; } else { jsonObject["chkTextAble"] = "0"; }
    if (chkBarcodeAble.Checked == true) { jsonObject["chkBarcodeAble"] = "1"; } else { jsonObject["chkBarcodeAble"] = "0"; }
    if (chkQrcodeAble.Checked == true) { jsonObject["chkQrcodeAble"] = "1"; } else { jsonObject["chkQrcodeAble"] = "0"; }
    if (chkLineAble.Checked == true) { jsonObject["chkLineAble"] = "1"; } else { jsonObject["chkLineAble"] = "0"; }
    if (chkRectangleAble.Checked == true) { jsonObject["chkRectangleAble"] = "1"; } else { jsonObject["chkRectangleAble"] = "0"; }

    //写入LogoAble
    JObject jObjLogoAble = new JObject();
    jObjLogoAble["txtLogoTop"] = txtLogoTop.Text;
    jObjLogoAble["txtLogoLeft"] = txtLogoLeft.Text;
    jObjLogoAble["txtLogoWidth"] = txtLogoWidth.Text;
    jObjLogoAble["txtLogoHeight"] = txtLogoHeight.Text;
    jObjLogoAble["txtLogoPath"] = txtLogoPath.Text;
    jObjLogoAble["txtLogoUrl"] = txtLogoUrl.Text;
    JArray arrayLogoAble = new JArray() { jObjLogoAble };
    jsonObject["LogoAble"] = arrayLogoAble;

    //写入TextAble
    JObject jObjTextAble = new JObject();
    jObjTextAble["txtTextTop"] = txtTextTop.Text;
    jObjTextAble["txtTextLeft"] = txtTextLeft.Text;
    jObjTextAble["txtTextWidth"] = txtTextWidth.Text;
    jObjTextAble["cBoxTextFontSize"] = cBoxTextFontSize.Text;
    jObjTextAble["cBoxTextFontFamily"] = cBoxTextFontFamily.Text;
    jObjTextAble["txtTextContent"] = txtTextContent.Text;
    jObjTextAble["cBoxTextType"] = cBoxTextType.Text;
    if (radioTextScale.Checked == true) { jObjTextAble["radioTextScale"] = "1"; } else { jObjTextAble["radioTextScale"] = "0"; }
    if (radioTextDirectWrap.Checked == true) { jObjTextAble["radioTextDirectWrap"] = "1"; } else { jObjTextAble["radioTextDirectWrap"] = "0"; }
    if (chkTextBold.Checked == true) { jObjTextAble["chkTextBold"] = "1"; } else { jObjTextAble["chkTextBold"] = "0"; }
    if (chkTextDirect.Checked == true) { jObjTextAble["chkTextDirect"] = "1"; } else { jObjTextAble["chkTextDirect"] = "0"; }
    JArray arrayTextAble = new JArray() { jObjTextAble };
    jsonObject["TextAble"] = arrayTextAble;

    //写入BarcodeAble
    JObject jObjBarcodeAble = new JObject();
    jObjBarcodeAble["cBoxBarcodeType"] = cBoxBarcodeType.Text;
    jObjBarcodeAble["txtBarcodeWidth"] = txtBarcodeWidth.Text;
    jObjBarcodeAble["txtBarcodeHeight"] = txtBarcodeHeight.Text;
    jObjBarcodeAble["txtBarcodeTop"] = txtBarcodeTop.Text;
    jObjBarcodeAble["txtBarcodeLeft"] = txtBarcodeLeft.Text;
    jObjBarcodeAble["txtBarCode"] = txtBarCode.Text;
    JArray arrayBarcodeAble = new JArray() { jObjBarcodeAble };
    jsonObject["BarcodeAble"] = arrayBarcodeAble;

    //写入QrcodeAble
    JObject jObjQrcodeAble = new JObject();
    jObjQrcodeAble["txtQrcodeWidth"] = txtQrcodeWidth.Text;
    jObjQrcodeAble["txtQrcodeTop"] = txtQrcodeTop.Text;
    jObjQrcodeAble["txtQrcodeLeft"] = txtQrcodeLeft.Text;
    jObjQrcodeAble["txtQRCode"] = txtQRCode.Text;
    jObjQrcodeAble["txtQrcodeAdjustNum"] = txtQrcodeAdjustNum.Text;
    JArray arrayQrcodeAble = new JArray() { jObjQrcodeAble };
    jsonObject["QrcodeAble"] = arrayQrcodeAble;

    //写入LineAble
    JObject jObjLineAble = new JObject();
    jObjLineAble["cBoxLineDirect"] = cBoxLineDirect.Text;
    jObjLineAble["txtLineTop"] = txtLineTop.Text;
    jObjLineAble["txtLineLeft"] = txtLineLeft.Text;
    jObjLineAble["txtLineLength"] = txtLineLength.Text;
    jObjLineAble["txtLineWidth"] = txtLineWidth.Text;
    jObjLineAble["cBoxLineStyle"] = cBoxLineStyle.Text;
    JArray arrayLineAble = new JArray() { jObjLineAble };
    jsonObject["LineAble"] = arrayLineAble;

    //写入RectangleAble
    JObject jObjRectangleAble = new JObject();
    jObjRectangleAble["txtRectangleTop"] = txtRectangleTop.Text;
    jObjRectangleAble["txtRectangleLeft"] = txtRectangleLeft.Text;
    jObjRectangleAble["txtRectangleWidth"] = txtRectangleWidth.Text;
    jObjRectangleAble["txtRectangleHeight"] = txtRectangleHeight.Text;
    jObjRectangleAble["txtRectangleBorderWidth"] = txtRectangleBorderWidth.Text;
    jObjRectangleAble["cBoxRectangleStyle"] = cBoxRectangleStyle.Text;
    JArray arrayRectangleAble = new JArray() { jObjRectangleAble };
    jsonObject["RectangleAble"] = arrayRectangleAble;

    //保存json文件
    string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObject, Newtonsoft.Json.Formatting.Indented);
    File.WriteAllText(tmpPath, output);
}
catch(Exception ex)
{
    MessageBox.Show("保存失败,错误原因:\r\n" + ex.Message, "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}

/// <summary>
/// 选择保存文件的名称以及路径  取消返回 空"";
/// </summary>
/// <param name="fileName"></param>
/// <param name="filter"></param>
/// <param name="title"></param>
/// <returns></returns>
public static string SaveFilePathName(string fileName = null, string filter = null, string title = null)
{
    string path = "";
    SaveFileDialog fbd = new SaveFileDialog();
    if (!string.IsNullOrEmpty(fileName))
    {
        fbd.FileName = fileName;
    }
    if (!string.IsNullOrEmpty(filter))
    {
        fbd.Filter = filter;// "Excel|*.xls;*.xlsx;";
    }
    if (!string.IsNullOrEmpty(title))
    {
        fbd.Title = title;// "保存为";
    }
    if (fbd.ShowDialog() == DialogResult.OK)
    {
        path = fbd.FileName;
    }
    return path;
}

=====读写base64图像=====

将图像写入json:
JObject obj = new JObject();
obj["img"] = Convert.ToBase64String(Imgbytes);
string jsonStr = obj.ToString();

将json中的图像取出:
JObject jsonObj = (JObject)JsonConvert.DeserializeObject(jsonStr);
string imgStr = (string)jsonObj["img"];
byte[] Imgbytes = Convert.fromBase64String(imgStr);

该文章在 2022/8/11 0:52:23 编辑过

  离 线  2022/8/11 0:52:22 
  本文章共有 0 页, 0 张回文,每页有 10 张回文 >> [ ]
页码:  
Copyright 2003-2024 ClickSun All Rights Reserved