咱們以以下的 Person
類舉例,其中包含了經常使用的數據類型:json
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime Birthday { get; set; }
public bool IsVIP { get; set; }
public float Account { get; set; }
public string[] Favorites { get; set; }
public string Remark { get; set; }
}
複製代碼
建立一個 Person
實例:數組
Person person = new Person
{
ID = 1,
Name = "張三",
Birthday = DateTime.Parse("2000-01-02"),
IsVIP = true,
Account = 12.34f,
Favorites = new string[] { "吃飯", "睡覺" }
};
複製代碼
JsonConvert.SerializeObject(person)
複製代碼
返回:bash
{"ID":1,"Name":"張三","Birthday":"2000-01-02T00:00:00","IsVIP":true,"Account":12.34,"Favorites":["吃飯","睡覺"],"Remark":null}
複製代碼
JsonConvert.SerializeObject(person, Formatting.Indented);
複製代碼
返回:spa
{
"ID": 1,
"Name": "張三",
"Birthday": "2000-01-02T00:00:00",
"IsVIP": true,
"Account": 12.34,
"Favorites": [
"吃飯",
"睡覺"
],
"Remark": null
}
複製代碼
private string JsonIndentation(string str) {
//string str = JsonConvert.SerializeObject(entity);
JsonSerializer serializer = new JsonSerializer();
TextReader tr = new StringReader(str);
JsonTextReader jtr = new JsonTextReader(tr);
object obj = serializer.Deserialize(jtr);
if (obj != null)
{
StringWriter textWriter = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
{
Formatting = Formatting.Indented,
Indentation = 4,
IndentChar = ' '
};
serializer.Serialize(jsonWriter, obj);
return textWriter.ToString();
}
else
{
return str;
}
}
複製代碼
或者:code
private string JsonIndentation(string json) {
JObject obj = JObject.Parse(json);
return obj.ToString();
}
複製代碼
JsonSerializerSettings settings = new JsonSerializerSettings();
// 設置日期格式
settings.DateFormatString = "yyyy-MM-dd";
// 忽略空值
settings.NullValueHandling = NullValueHandling.Ignore;
// 縮進
settings.Formatting = Formatting.Indented;
JsonConvert.SerializeObject(person, settings);
複製代碼
返回:orm
{
"ID": 1,
"Name": "張三",
"Birthday": "2000-01-02",
"IsVIP": true,
"Account": 12.34,
"Favorites": [
"吃飯",
"睡覺"
]
}
複製代碼
JsonConvert.DeserializeObject<Person>(json);
複製代碼
JObject obj = new JObject();
obj.Add("ID", 1);
obj.Add("Name", "張三");
obj.Add("Birthday", DateTime.Parse("2000-01-02"));
obj.Add("IsVIP", true);
obj.Add("Account", 12.34f);
// 建立數組
JArray array = new JArray();
array.Add(new JValue("吃飯"));
array.Add(new JValue("睡覺"));
obj.Add("Favorites", array);
obj.Add("Remark", null);
複製代碼
string json = "{\"ID\":1,\"Name\":\"張三\",\"Birthday\":\"2000-01-02T00:00:00\",\"IsVIP\":true,\"Account\":12.34,\"Favorites\":[\"吃飯\",\"睡覺\"],\"Remark\":null}";
JObject obj = JObject.Parse(json);
複製代碼
JObject obj = JObject.FromObject(person);
複製代碼
JObject obj = JObject.FromObject(new { name = "jack", age = 18 });
複製代碼
顯示:對象
{
"name": "jack",
"age": 18
}
複製代碼
int id;
if (obj["ID"] != null)
id = obj["ID"].Value<int>();
複製代碼
Newtonsoft.Json.Linq 不支持直接獲取數組,可是能夠獲取 List
,而後再轉化爲數組。字符串
string[] favorites;
if (obj["Favorites"] != null)
favorites = obj["Favorites"].Value<List<string>>().ToArray();
複製代碼