前段时间都是遇到技术上的问题,然后就大篇幅的搜索,看看就算了,最多也是转载一下,结果到头来是似懂非懂,真正自己用的时候,总觉得力不从心。对于一个程序员来说,以这种状态下去,肯定不行的。所以,我们不但要会搜索,还要会主动去实践,要举一反三,我想这样才能真正学到点东西,如果再找一种适合自己的方式整理一下要点,这样再好不过了。废话不多说了,进入今天的主题:Newtonsoft.Josn。Newtonsoft.Json,是一款.NET中开源的Json序列化和反序列化类库(下载地址http://json.codeplex.com/)。
下面我讲以我自己写的一个小demo让大家理解一下json与其他格式的转换,欢迎大家拍砖~
一、这是我的demo结构:
二、这是我自己写的Josn帮助类JsonHelper.cs,是对Json序列化和反序列化的简单封装:
public static class JsonHelper
{
///
/// Xml文件转Json
///
/// xml文件路径
///
public static string Xml2Json(string path)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(path); // 通过xml的路径读取xml文件
string json = JsonConvert.SerializeXmlNode(doc.DocumentElement, Newtonsoft.Json.Formatting.Indented, true);
return json;
}
catch (Exception e)
{
SystemLog.Error("Xml2Json: " + e);
throw;
}
}
///
/// Json转Xml
///
///
///
public static void Json2Xml(string json, string savePath)
{
try
{
XmlDocument doc = JsonConvert.DeserializeXmlNode(json, "root");
doc.Save(savePath);
}
catch (Exception e)
{
SystemLog.Error("Json2Xml: " + e);
throw;
}
}
///
/// Json转Assemble
///
///
///
///
public static List Json2Assemble(string json) where T : class
{
try
{
//JsonConvert将JSON中的属性转换为类的属性
var list = JsonConvert.DeserializeObject>(json);
return list;
}
catch (Exception e)
{
SystemLog.Error("Json2Assemble: " + e);
throw;
}
}
///
/// Assemble转Json
///
///
///
///
public static string Assemble2Json(List list) where T : class
{
try
{
string json = JsonConvert.SerializeObject(list,Newtonsoft.Json.Formatting.Indented);
return json;
}
catch (Exception e)
{
SystemLog.Error("Assemble2Json: "+ e);
throw;
}
}
///
/// Json转Object
///
///
///
///
public static T Json2Object(string json) where T : class
{
try
{
//JsonConvert将JSON中的属性转换为类的属性
T entity = JsonConvert.DeserializeObject(json);
return entity;
}
catch (Exception e)
{
SystemLog.Error("Json2Object: " + e);
throw;
}
}
///
/// Assemble转Json
///
///
///
///
public static string Object2Json(T entity) where T : class
{
try
{
string json = JsonConvert.SerializeObject(entity, Newtonsoft.Json.Formatting.Indented);
return json;
}
catch (Exception e)
{
SystemLog.Error("Object2Json: " + e);
throw;
}
}
///
/// Dictonary转Json
///
///
///
///
///
public static string Dictonary2Json(Dictionary dictionary)
{
try
{
//将字典转换成Json字符串
string json = JsonConvert.SerializeObject(dictionary, Newtonsoft.Json.Formatting.Indented);
return json;
}
catch (Exception e)
{
SystemLog.Error("Dictonary2Json: "+ e);
throw;
}
}
///
/// Json转Dictionary
///
///
///
///
///
public static Dictionary Json2Dictionary(string json)
{
try
{
Dictionary dictionary = JsonConvert.DeserializeObject>(json);
return dictionary;
}
catch (Exception e)
{
SystemLog.Error("Json2Dictionary: "+ e);
throw;
}
}
}
三、下面是对这个帮助类的简单应用,加强理解:
private void xml2json_Click(object sender, EventArgs e)
{
string xmlPath = Application.StartupPath + "\\company.xml";
string jsonStr = JsonHelper.Xml2Json(xmlPath);
lblResult.Text = "xml2json: " + jsonStr + "\n";
}
private void json2xml_Click(object sender, EventArgs e)
{
string json = "{\"name\":\"king\",\"age\":\"20\",\"job\":\"code\"}";
string savePath = Application.StartupPath + "\\person.xml";
JsonHelper.Json2Xml(json, savePath);
lblResult.Text = "json2xml success,please see: " + savePath;
}
private void Json2Object_Click(object sender, EventArgs e)
{
//定义一个JSON字符串
string jsonStr = "[{\"ChineseName\":\"John\",\"EnglishName\": \"Doe\",\"Sex\":\"man\",\"Age\":\"20\",\"WhichClass\":\"class1\"}," +
"{\"ChineseName\":\"Cara\",\"EnglishName\": \"cr\",\"Sex\":\"woman\",\"Age\":\"30\",\"WhichClass\":\"class2\"}]";
List sudentList = JsonHelper.Json2Assemble(jsonStr);
for (int i = 0; i < 2; i++)
{
lblResult.Text += sudentList[i].ChineseName + "\n";
lblResult.Text += sudentList[i].EnglishName + "\n";
lblResult.Text += sudentList[i].Sex + "\n";
lblResult.Text += sudentList[i].Age + "\n";
lblResult.Text += sudentList[i].WhichClass + "\n";
}
}
private void Object2Json_Click(object sender, EventArgs e)
{
//string jsonStr = "[{\"ChineseName\":\"John\",\"EnglishName\": \"Doe\",\"Sex\":\"man\",\"Age\":\"20\",\"WhichClass\":\"class1\"}," +
// "{\"ChineseName\":\"Cara\",\"EnglishName\": \"cr\",\"Sex\":\"woman\",\"Age\":\"30\",\"WhichClass\":\"class2\"}]";
//List sudentList = JsonHelper.Json2Assemble(jsonStr);
//创建一个集合
List> list = new List>
{
new List{"James","Jo","Jess"},
new List{"1001","1002","1003"}
};
string jsonResult = JsonHelper.Assemble2Json(list);
lblResult.Text = jsonResult;
}
private void Dic2Json_Click(object sender, EventArgs e)
{
//创建一个字典
Dictionary dic = new Dictionary
{
{"King", 20},
{"John", 30}
};
string json = JsonHelper.Dictonary2Json(dic);
lblResult.Text = json;
}
private void Json2Dic_Click(object sender, EventArgs e)
{
string json = "{\"name\":\"king\",\"age\":\"20\",\"job\":\"code\"}";
Dictionary dictionary = JsonHelper.Json2Dictionary(json);
foreach (var child in dictionary)
{
lblResult.Text += child.Key + "\n";
lblResult.Text += child.Value + "\n\n";
}
}
private void button2_Click(object sender, EventArgs e)
{
string json = "{\"ChineseName\":\"John\",\"EnglishName\": \"Doe\",\"Sex\":\"man\",\"Age\":\"20\",\"WhichClass\":\"class1\"}";
Student student = JsonHelper.Json2Object(json);
lblResult.Text += student.ChineseName;
lblResult.Text += student.EnglishName;
lblResult.Text += student.Sex;
lblResult.Text += student.Age;
lblResult.Text += student.WhichClass;
}
private void button1_Click(object sender, EventArgs e)
{
Student student = new Student();
student.ChineseName = "King";
lblResult.Text = JsonHelper.Object2Json(student);
}
这是Student实体类:
public class Student
{
public string ChineseName;
public string EnglishName;
public string Sex;
public int Age;
public string WhichClass;
}
四、使用Json的时候,需要注意以下几点:
1. 主要json字符串的书写格式,一开始我搞了很久才知道是这样写的,虽然看起来有点奇怪,但它就是要这样写。
如:
string jsonStr = "[{\"ChineseName\":\"John\",\"EnglishName\": \"Doe\",\"Sex\":\"man\",\"Age\":\"20\",\"WhichClass\":\"class1\"}," +
"{\"ChineseName\":\"Cara\",\"EnglishName\": \"cr\",\"Sex\":\"woman\",\"Age\":\"30\",\"WhichClass\":\"class2\"}]";
2.格式转换时,可以通过
Newtonsoft.Json.Formatting.Indented
设置一下输入格式,方便对json内容的理解
之前在我也转了一篇关于json的文章,整理得不错,大家也可以去看看,多学习点
http://blog.csdn.net/kingsea168/article/details/49749191
接下来的文章,应该要写写关于json的消息传送方面的内容,这次就先暂时写到这了......