C#
中使用Json
,安装Newtonsoft.json
依赖
读取json
文件
注意:检查json文件的编码类型,是否为UTF-8。不是的话,读取到的中文会乱码
方法:json
文件使用记事本打开,界面下方会显示编码类型。若不是,将文件另存为,更改即可。
private JObject ReadJsonFile(string folder, string fileName){
string filePath = System.IO.Path.Combine(folder + "/" + fileName);
using (System.IO.StreamReader file = System.IO.File.OpenText(filePath))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject jObject = (JObject)JToken.ReadFrom(reader);
return jObject;
}
}
}
写入json
文件
private void WriteJsonFile(string folder, string fileName, JObject jObject){
string filePath = System.IO.Path.Combine(folder + "/" + fileName);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath))
{
file.Write(jObject.ToString());
}
}
几种常用类型
JObject
用于操作json对象
JToken
用于存放linq查询的结果
JArray
用于json数组
JValue
表示数组中的值
JProperty
表示对象的属性
JObject jo = new JObject(){{"name","张珊"},{"age",18}};
// {"name":"张三",“age”:18}
JToken jname = jo["Name"];
string[] girlFriends = {"韩梅梅","橘朵"};
JArray ja = new JArray();
foreach(var name in girlFriends){
ja.Add(new JValue(name));
}
jo.Add(new JProperty("girlFriends",ja));
几种常用API
JObject.Parse
用于将字符串格式转成JObject
jo.ToObject<T>
用于将 JObject
类型转化成 实体类
JObject.FromObject
用于将 实体类 转化成 JObject
LINQ to JSON
查询
JObject o = JObject.Parse(@"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
List<string> allDrives = o["Drives"].Select(t => (string)t).ToList();//["DVD read/writer","500 gigabyte hard drive"]
新建
List<Post> GetPosts()
{
List<Post> posts = new List<Post>() {
new Post(){ Title = "A",Description ="A is a",Link = "http://www.a.com",Categories = new List<string>(){ "apple","alpha"} },
new Post(){ Title = "B",Description ="B is b",Link = "http://www.b.com",Categories = new List<string>(){ "belt","baby"} },
new Post(){ Title = "C",Description ="C is c",Link = "http://www.c.com",Categories = new List<string>(){ "cut","city"} }
};
return posts;
}
List<Post> posts = GetPosts();
JArray itemJArray = new JArray(
from p in posts
orderby p.Title
select new JObject(
new JProperty("title", p.Title),
new JProperty("description", p.Description),
new JProperty("link", p.Link),
new JProperty("category",
new JArray(
from c in p.Categories
select new JValue(c)
)
)
)
);
class Post
{
public string? Title;
public string? Description;
public string? Link;
public List<string>? Categories;
}
对象变JObject
JObject pp = JObject.FromObject(new
{
channel = new
{
title = "D",
link = "http://www.d.com",
description = "D is d",
item =
from p in posts
orderby p.Title
select new
{
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories
}
}
});
path
获取值
pp.SelectToken("channel.item[0].title")
序列化
string aa = JsonConvert.SerializeObject(posts[0]);//对象序列化(变成json格式的字符串)
Post ppp = JsonConvert.DeserializeObject<Post>(aa);//json字符串 反序列化 (变成对象)
string json = @"{""key1"":""value1"",""key2"":""value2""}";
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);