官方文档
https://www.newtonsoft.com/json/help/html/t_newtonsoft_json_linq_jobject.htm
安装
序列化对象
对象实力类
class Item
{
private string name;
private int level;
private int status;
public string Name
{
get => name;
set => name = value;
}
public int Level
{
get => level;
set => level = value;
}
public int Status
{
get => status;
set => status = value;
}
}
Item item = new Item();
item.Level = 1;
item.Name = "Hello";
item.Status = 1;
string json = JsonConvert.SerializeObject(item);
{
"Name": "Hello",
"Level": 1,
"Status": 1
}
解析
string json ="{\"0\":{\"Name\":null,\"Level\":100,\"Status\":256},\"1\":{\"Name\":null,\"Level\":0,\"Status\":256},\"2\":{\"Name\":null,\"Level\":0,\"Status\":256},\"3\":{\"Name\":null,\"Level\":0,\"Status\":256},\"4\":{\"Name\":null,\"Level\":0,\"Status\":256},\"5\":{\"Name\":null,\"Level\":0,\"Status\":256},\"6\":{\"Name\":null,\"Level\":0,\"Status\":256},\"7\":{\"Name\":null,\"Level\":0,\"Status\":256},\"8\":{\"Name\":null,\"Level\":0,\"Status\":256},\"9\":{\"Name\":null,\"Level\":0,\"Status\":256},\"10\":{\"Name\":null,\"Level\":0,\"Status\":256},\"11\":{\"Name\":null,\"Level\":0,\"Status\":256}}";
// 解析方式1
JObject jObject = JObject.Parse(json);
// 解析方式2
JObject jObject = JsonConvert.DeserializeObject<JObject>(json);
// 取值 方式1
int level = (int)jObject["0"]["Level"];
// 取值 方式2
JObject value = jObject.Value<JObject>("0");
int level = value.Value<int >("Level");
格式化json
https://www.cnblogs.com/unintersky/p/3884712.html
public static string ConvertJsonString(string str)
{
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;
}
}