Json读取写入文本

新建一个名字叫做Player.txt的文本文档。Json的格式在此不在赘述。

{
"Name": "小明",
"Age": 12,
"PlayerList": [
{
"username": "admin",
"userpass": "admin",
"sex": "女"
},
{
"username": "LiBai",
"userpass": "123",
"sex": "男"
},
{
"username": "XiaoMing",
"userpass": "456",
"sex": "男"
}
]
}

写完之后在www.bejson.com里在验证一下json的格式是否正确。

新建一个Player.cs类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
class Players
{
    public string Name { get; set; }//定义属性
    public int Age { get; set; }
    public List PlayerList { get; set; }

//重写ToString()方法可以看输出格式。
    public override string ToString()
  {
    return string.Format("Name:" + Name + "Age" + Age + "PlayerMessage" + PlayerList);
  }
  }
}

在主程序Program.cs中写入

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LitJson;
using System.IO;
namespace ConsoleApplication5
{
  class Program
  {
    static void Main(string[] args)
    {
      //主角信息的解析
      //Players ss = JsonMapper.ToObject(File.ReadAllText("Player.txt"));
      //foreach (var item in ss.PlayerList)
      //{
      // Console.WriteLine(item);
      //}
      //Console.WriteLine(ss);
      //写入文本文件
      Players p = new Players();
      p.Name = "h";
      p.Age = 5;
      string s = JsonMapper.ToJson(p);
      using (FileStream fsw = new FileStream("Player.txt", FileMode.OpenOrCreate, FileAccess.Write)) {//相对路径在项目之中

      byte[] b = Encoding.Default.GetBytes(s);
      fsw.Write(b, 0, b.Length);
    }
  }
  }
}

运行结果:

Json读取写入文本_第1张图片


 

 

写入文本(注意:中文会乱码)

Json读取写入文本_第2张图片

 

 

 

 

 

你可能感兴趣的:(C#)