using Newtonsoft.Json.Linq;
class Program
{
static void Main()
{
// 创建一个 JSON 对象
JObject jsonObject = new JObject
{
{ "name", "John" },
{ "age", 30 },
{ "isStudent", false }
};
// 添加嵌套的 JSON 对象
jsonObject["address"] = new JObject
{
{ "street", "123 Main St" },
{ "city", "Anytown" },
{ "state", "CA" }
};
// 将 JSON 对象转换为字符串
string jsonString = jsonObject.ToString();
Console.WriteLine("JSON String: " + jsonString);
// 从 JSON 字符串解析为 JSON 对象
string jsonInput = "{\"name\":\"Jane\",\"age\":25,\"isStudent\":true}";
JObject parsedObject = JObject.Parse(jsonInput);
Console.WriteLine("Parsed JSON Object: " + parsedObject);
// 访问 JSON 对象中的属性
string name = (string)parsedObject["name"];
int age = (int)parsedObject["age"];
bool isStudent = (bool)parsedObject["isStudent"];
Console.WriteLine($"Name: {name}, Age: {age}, Is Student: {isStudent}");
}
}
JObject 类创建一个 JSON 对象,并添加键值对。JObject 作为值添加到现有的 JSON 对象中,形成嵌套结构。ToString() 方法将 JObject 转换为 JSON 字符串。JObject.Parse() 方法将 JSON 字符串解析为 JObject。JObject 中的值,并将其转换为相应的类型(如 string、int、bool 等)。上一篇:c# 数组添加元素
下一篇:c#字符串是否包含某个字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站