J S O N JSON JSON
1.JSON的构造
JSON是比XML更常用的一个文本数据格式
需借助于第3方库实现
Newtonsoft.Json
https://www.newtonsoft.com/json
JObject 用于操作JSON对象
JArray 用语操作JSON数组
JValue 表示数组中的值
JProperty 表示对象中的属性,以"key/value"形式
JToken 用于存放Linq to JSON查询后的结果
删除 JSON 数组中的某个元素
JArray jArray = JArray.Parse(json);
jArray.RemoveAt(0);
删除 JSON 中的某个属性:
JObject jObject = (JObject)jToken;
jObject.Remove("name");
两个Jobject进行合并
// 首先,我们需要将两个JSON数据转换为C#对象
JObject obj1 = JObject.Parse(json1);
JObject obj2 = JObject.Parse(json2);
// 然后,我们将两个对象合并
obj1.Merge(obj2);
// 最后,将合并后的对象转换为JSON字符串
string mergedJson = obj1.ToString();
将自己的类转json类进行存储(JObject.FromObject(youtobj))
AlgoProject algo = new AlgoProject();
algo.Name = frm.Values[0];
algo.Task = frm.Values[1];
algo.Note = frm.Values[2];
allalgo.algoProject = algo;
JObject j1 = new JObject();
j1["1"] = JObject.FromObject(algo);
添加json内容
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Major;
using Newtonsoft.Json.Linq;
namespace CSharp基础语法
{
class Program
{
static void Main(string[] args)
{
JObject j = new JObject();
j["id"] = 123456; // 通过索引器添加
j["name"] = "major";
j.Add("sex", true); // 通过方法调用添加
j.Add("phone", "1234567890");
JArray colors = new JArray();
colors.Add("red");
colors.Add("yellow");
colors.Add("blue");
j.Add("colors", colors);
string jsonstr = j.ToString();
Console.WriteLine(jsonstr);
}
}
}
;
2.JSON的解析
演示:从JSQN字符串中提取字段
1 添加Newtonsoft.Json.dll
2 将String —> JObject
3 从JObject中提取字段
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Major;
using Newtonsoft.Json.Linq;
namespace CSharp基础语法
{
class Program
{
public static string CreateJSON()
{
JObject j = new JObject();
j["id"] = 123456; // 通过索引器添加
j["name"] = "major";
j.Add("sex", true); // 通过方法调用添加
j.Add("phone", "1234567890");
JArray colors = new JArray();
colors.Add("red");
colors.Add("yellow");
colors.Add("blue");
j.Add("colors", colors);
string jsonstr = j.ToString();
return jsonstr;
}
static void Main(string[] args)
{
string jsonstr = CreateJSON();
// string ---> JObject
JObject j2 = JObject.Parse(jsonstr);
// 提取各个字段
int id = (int)j2["id"];
bool sex = (bool)j2["sex"];
Console.WriteLine("学号:" + id + "性别:" + sex);
// 判断一个字符是否存在
if (j2.ContainsKey("name"))
{
string name = (string)j2.GetValue("name");
Console.WriteLine("姓名:" + name);
}
// 取得一个Array
JArray colors = (JArray)j2["colors"];
for(int i = 0; i < colors.Count; i++)
{
string c = (string)colors[i];
Console.WriteLine("color:" + c);
}
}
}
}
;
3.对象的序列化
对象的序列化:比如,Student类
1序列化Serialize : Student ---> JSON String
2反序列化Deserilize : JSON String ---> Student
C#里把Student称为实体类(相当于Java里的POJO类)
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Major;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CSharp基础语法
{
class Program
{
static void Main(string[] args)
{
Student stu = new Student();
stu.Id = 123456;
stu.Name = "major";
stu.Sex = true;
stu.Phone = "1234567890";
stu.SetAddress("无锡市");
// POJO <==> JSON String
string jsonstr = JsonConvert.SerializeObject(stu);
Student pojo = JsonConvert.DeserializeObject<Student> (jsonstr );
// POJO <==> JObject
JObject j2 = JObject.FromObject(stu);
Student s2 = j2.ToObject<Student>();
}
}
}
;
显然,Newtonsoft.Json里使用了反射技术对实体类的要求:
·所有的属性可以get;set;
-所有的字段有Getter/Setter方法
属性和字段都可以完成反射,但属性在C#里更为常见
字段是类用public修饰符所公开的变量,属性是对字段的封装,属性的实质是方法{get;set;}方法。
字段就是类内部用来存储数据,属性是类提供给外部调用时设置或读取 一个值。
JSONHelper
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace TestUI
{
public class JSONHelper
{
public static bool UpdateJSON(object data, string input_file,string output_file, Type type)
{
//string json = JsonConvert.SerializeObject(data);
//File.WriteAllText(file, json);
return true;
}
public static bool AppendJSON(JObject data, string key, string jsonfilePath)
{
// 如果文件不存在,则创建
if (!File.Exists(jsonfilePath))
{
JObject j1 = new JObject();
j1[key] = data;
string json = JsonConvert.SerializeObject(j1);
File.WriteAllText(jsonfilePath, json);
return true;
}
string jsonString = "";
using (StreamReader reader = new StreamReader(jsonfilePath))
{
jsonString = reader.ReadToEnd();
}
// 字符串转JObject
JObject rawjsonObject = JObject.Parse(jsonString);
rawjsonObject[key] = data;
string appendjson = JsonConvert.SerializeObject(rawjsonObject);
// 保存json
File.WriteAllText(jsonfilePath, appendjson);
return true;
}
public static bool WriteJSON(object data, string file)
{
string json = JsonConvert.SerializeObject(data);
File.WriteAllText(file, json);
return true;
}
public static JObject ReadJSON(string jsonfilePath)
{
string jsonString = "";
using (StreamReader reader = new StreamReader(jsonfilePath))
{
jsonString = reader.ReadToEnd();
}
JObject jsonObject = JObject.Parse(jsonString);
return jsonObject;
}
}
}
C#操作字典
//定义一个字典变量
static Dictionary dicPerson = new Dictionary();
public static void LearnDictionaryInfo()
{
//添加键值
Person p1 = new Person("hjc", 22);
Person p2 = new Person("tf", 21);
dicPerson.Add(0, p1); //方式1
dicPerson[1] = p2; //方式2
//取值
Console.WriteLine("\n");
Console.WriteLine("取值 name:" + dicPerson[0].name + "—" + "age:" + dicPerson[0].age);
//改值
Console.WriteLine("\n");
dicPerson[1].age = 20;
Console.WriteLine("改值 name:" + dicPerson[1].name + "—" + "age:" + dicPerson[1].age);
//遍历key
Console.WriteLine("\n");
Console.WriteLine("遍历 key");
foreach (int key in dicPerson.Keys)
{
string id = "用户ID:" + key;
string str = string.Format("name:{0} age:{1}", dicPerson[key].name, dicPerson[key].age);
Console.WriteLine(id + "\t" + str);
}
//遍历value
Console.WriteLine("\n");
Console.WriteLine("遍历 value");
foreach (Person value in dicPerson.Values)
{
string str = string.Format("name:{0} age:{1}", value.name, value.age);
Console.WriteLine(str);
}
//遍历字典
Console.WriteLine("\n");
Console.WriteLine("遍历字典");
foreach (KeyValuePair kvp in dicPerson)
{
string str = string.Format("key:{0}/name:{1}/age:{2}", kvp.Key, kvp.Value.name, kvp.Value.age);
Console.WriteLine(str);
}
// 删除元素
Console.WriteLine("\n");
Console.WriteLine("删除元素");
if (dicPerson.ContainsKey(1)) //如果存在
dicPerson.Remove(1);
foreach (Person value in dicPerson.Values)
{
string str = string.Format("name:{0} age:{1}", value.name, value.age);
Console.WriteLine(str);
}
//清除所有的元素
dicPerson.Clear();
Console.Read();
判断字典中是否包含某值
Dictionary<string, string> dict = new Dictionary<string, string>();
string key="a";
string value="";
if(dict.ContainsKey(key)==false){
dict[key]="1";
}