“抛弃数据库”是标题党哈,只是数据量小的桌面应用可以不用就尽量不用了罢。
于是想到了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!