抛弃数据库---Newtonsoft.Json 对象转成JSON文件简单实例,JSON没有反斜杠

“抛弃数据库”是标题党哈,只是数据量小的桌面应用可以不用就尽量不用了罢。

于是想到了JSON,但是发现用Newtonsoft.Json时,序列化对象后无论咋样都会有双引号和反斜杠,以至于反序列化失败。

小问题,但是折腾了好久,随便写了个测试POST上来,有很多代码不规范的地方请勿喷。

======================================

建立一个名称为testJson 的.net Framework 4.7.2的桌面应用程序;

拖两个textBOX和一个Button做测试,在NuGet中安装Newtonsoft.Json ;

json文件将自动生成在应用程序目录下。

下面是代码(C#):

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace testJson
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        JArray Jobj = new JArray();

        string fp = System.Windows.Forms.Application.StartupPath + "\\info.json";
        private void Form1_Load(object sender, EventArgs e)
        {

            if (!File.Exists(fp))  // 判断是否已有相同文件 
            {
                FileStream fs1 = new FileStream(fp, FileMode.Create, FileAccess.ReadWrite);
                fs1.Close();
            }
 
              //  Jobj = (JArray)JsonConvert.DeserializeObject(File.ReadAllText(fp));  //将json文件反序列化成JArray
              //  txt_memo.Text = Jobj[0]["description"].ToString();  //测试输出一下到textbox
 
        }

        public class testClass
        {
            public string topic { get;set;}
            public string description { get;set;}
        }
   
        private void button1_Click(object sender, EventArgs e)
        {
            testClass testA = new testClass();
            testA.topic = txt_topic.Text;
            testA.description = txt_memo.Text;

            string jsondata = JsonConvert.SerializeObject(testA);  

            var token = JToken.Parse(jsondata);
            Jobj.Add(token);

            File.WriteAllText(fp, Jobj.ToString());

        }
    }
}

Thanks for the stackOverflow! 

Have a NiceDay!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值