Json序列化
2021-02-20 07:34
标签:obj cti 年龄 index div json序列化 address soft on() JSON基本数据格式: 1.JSON对象 2.JSON数组 3.复杂一点的JSONObject 4.复杂一点的JSONArray 5.更复杂的 刚开始接触的时候,不是很懂,为什么要写这几种格式,是因为有时候会拼接json字符串,所以熟悉json格式很有必要。 JSON序列化对象: using Newtonsoft.Json;(别忘记引用) 结果: JSON序列化list集合: 结果: JSON序列化Dictionary字典: 结果: 序列化的结果保存指定文件: 基于枚举的JsonConverters转换器: 结果: Json序列化 标签:obj cti 年龄 index div json序列化 address soft on() 原文地址:https://www.cnblogs.com/-zzc/p/10191735.html{"name":"很帅很低调" , "age":20 , "Handsome":true}
[{"name":"很帅很低调" , "age":20 , "Handsome":true},{"name":"弟弟" , "age":18 , "Handsome":false}]
{"name":"很帅很低调", "age":20, "Handsome":true, "address":{"street":"湖北", "city":"武汉","country":"中国"}}
[{"name":"很帅很低调","age":20,"Handsome":true,"address":{"street":"湖北","city":"武汉","country":"中国"}},{"name":"弟弟","age":18,"Handsome":false,"address":{"street":"湖北","city":"黄冈","country":"中国"}}]
{
"video": {
"id": "29BA6ACE7A9427489C33DC5901307461",
"title": "体验课",
"desp": "",
"tags": " ",
"duration": 503,
"category": "07AD1E11DBE6FDFC",
"image": "http://2.img.bokecc.com/comimage/0DD1F081022C163E/2016-03-09/29BA6ACE7A9427489C33DC5901307461-0.jpg",
"imageindex": 0,
"image-alternate": [{
"index": 0,
"url": "http://2.img.bokecc.com/comimage/0DD1F081022C163E/2016-03-09/29BA6ACE7A9427489C33DC5901307461-0/0.jpg"
}, {
"index": 1,
"url": "http://2.img.bokecc.com/comimage/0DD1F081022C163E/2016-03-09/29BA6ACE7A9427489C33DC5901307461-0/1.jpg"
}, {
"index": 2,
"url": "http://2.img.bokecc.com/comimage/0DD1F081022C163E/2016-03-09/29BA6ACE7A9427489C33DC5901307461-0/2.jpg"
}, {
"index": 3,
"url": "http://2.img.bokecc.com/comimage/0DD1F081022C163E/2016-03-09/29BA6ACE7A9427489C33DC5901307461-0/3.jpg"
}]
},
"type": 1,
"play": true
}
public class Root
{
//序列化时指定属性在JSON中的顺序
[JsonProperty(Order = 0)]
public string name { get; set; }
[JsonProperty(Order = 1)]
public int age { get; set; }
[JsonProperty(Order = 2)]
public string Handsome { get; set; }
}
public static string SerJson()
{
Root root = new Root
{
name = "很帅很低调",
age = 20,
Handsome = "true"
};
string json = JsonConvert.SerializeObject(root);
return json;
}{"name":"很帅很低调" , "age":20 , "Handsome":true}
public static string ListJson()
{
Liststring> videogames = new Liststring> { "名字", "性别", "年龄" };
string json = JsonConvert.SerializeObject(videogames);
return json;
}
["名字","性别","年龄"]
public static string DicJson()
{
Dictionarystring,int> dic = new Dictionarystring,int>
{
{ "ming",20},
{ "uzi",21},
{ "the rang",22}
};
string json = JsonConvert.SerializeObject(dic, Formatting.Indented);//Formatting.Indented形成良好的格式
return json;
}{
"ming": 20,
"uzi": 21,
"the rang": 22
}
public static void FileJosn()
{
Root root = new Root
{
name = "很帅很低调",
age = 20,
Handsome = "true"
};
using (StreamWriter file = File.CreateText(@"e:\\file.json"))
{
JsonSerializer jsonSerializer = new JsonSerializer();
jsonSerializer.Serialize(file, root);
}
}
public enum StringEnum{ one = 1,two = 2,three = 3}
public static void JsonEnum()
{
List
[1,3]