0%

JSON字符串

C#生成方法

Newtonsoft

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
String apiClass = "apiClass";
String apiCommand = "apiCommand";
JObject postedJObject = new JObject();
postedJObject.Add("class", apiClass);
postedJObject.Add("cmd", apiCommand);

String param1 = "param1";
String param2 = "param2";
JObject apiJsonParam = new JObject();
apiJsonParam.Add("param1", param1);
apiJsonParam.Add("param2", param2);
postedJObject.Add("param", apiJsonParam);
apiJsonParam["param1"] = param1);
apiJsonParam["param2"] = param2);
postedJObject["param"] = apiJsonParam;

JArray jArray = new JArray();
JObject arr1 = new JObject();
arr1.Add("arr1", "this is arr1");
jArray.Add(arr1);
JObject arr2 = new JObject();
arr2.Add("arr2", "this is arr2");
jArray.Add(arr2);
postedJObject.Add("jarray", jArray);
String paramString = postedJObject.ToString(Newtonsoft.Json.Formatting.Indented, null);

输出结果为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"class": "apiClass",
"cmd": "apiCommand",
"param": {
"param1": "param1",
"param2": "param2"
},
"jarray": [
{
"arr1": "this is arr1"
},
{
"arr2": "this is arr2"
}
]
}

序列化

string StrJson = JsonConvert.SerializeObject(Classobj);

读取保存JSON文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
string json = string.Empty;
using (FileStream fs = new FileStream(filepath, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312")))
{
json = sr.ReadToEnd().ToString();
}
}

string json = GetFileJson(filepath);

using (FileStream fs = new FileStream(fileFullPath, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
{
fs.Seek(0, SeekOrigin.Begin);
fs.SetLength(0);
using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
{
sw.WriteLine(strJson);
}
}

反序列化

ClassA a = JsonConvert.DeserializeObject(strResult);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

List<Student> lstStuModel = new List<Student>()
{
new Student(){ID=1,Name="Name1",Age=250,Sex="男"},
new Student(){ID=2,Name="Name2",Age=300,Sex="女"}
};

//Json.NET序列化
string jsonData = JsonConvert.SerializeObject(lstStuModel);

//Json.NET反序列化
string json = @"{ 'Name':'Name1','Age':'3000','ID':'1','Sex':'女'}";
Student descJsonStu = JsonConvert.DeserializeObject<Student>(json);//反序列化
Student descJsonStu = JsonConvert.DeserializeObject<Student>(json, Formatting.Indented);//反序列化, 加缩进
Console.WriteLine(string.Format("反序列化: ID={0},Name={1},Sex={2},Sex={3}", descJsonStu.ID, descJsonStu.Name, descJsonStu.Age, descJsonStu.Sex));
Console.ReadKey();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//序列化时默认都是处理公共成员,如果需要处理非公共成员,就要在该成员上加特性[JsonProperty]
//类中所有公有成员会被序列化,如果不想被序列化,可以用特性JsonIgnore
[JsonObject(MemberSerialization.OptOut)]
class TestItem
{
[JsonProperty]
private int testNo;
[JsonIgnore]
public string testItem;
public string testValue;
}
//所有的成员不会被序列化,类中的成员只有标有特性JsonProperty的才会被序列化
[JsonObject(MemberSerialization.OptIn)]
class TestItem1
{
[JsonIgnore]
public string testItem;
public string testValue;
}

其他格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//序列化时忽略空值
public class Data
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string itemResult;

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string equipmentData;
}
//自定义时间格式
class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
base.DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
}
}
[JsonConverter(typeof(CustomDateTimeConverter))]
public DateTime sendTime;

//自定义序列化名称
[JsonProperty(PropertyName = "CName")]
public string Name { get; set; }

全局设置(常用)

1
2
3
4
5
6
7
8
9
10
11
Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() => {
//日期类型默认格式化处理
setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
setting.DateFormatString = "yyyy-MM-dd HH:mm:ss.ffff";
//空值处理
setting.NullValueHandling = NullValueHandling.Ignore;
//自定义类型转换
setting.Converters.Add(new 自定义类型转换());
return setting;
});
1
2
3
4
5
6
7
8
9
10
Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings {
//日期类型默认格式化处理
setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
setting.DateFormatString = "yyyy-MM-dd HH:mm:ss.ffff";
//空值处理
setting.NullValueHandling = NullValueHandling.Ignore;
//自定义类型转换
setting.Converters.Add(new 自定义类型转换());
return setting;
});

匿名类型生成Json字符串

1
2
3
4
5
6
7
8
9
10
11
var obj = new {
Name = "Jone",
Age = 18,
Address = new {
Street = "123 St",
City = "Shanghai"
}
};

string jsonString = JsonConvert.SerializeObject(obj, Formatting.Indented);