using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
public class Program
{
public static void Main()
{
string json = @"{
'Name': 'John Doe',
'Age': 30,
'Address': {
'Street': '123 Main St',
'City': 'Anytown'
}
}";
JObject jObject = JObject.Parse(json);
Person person = jObject.ToObject<Person>();
Console.WriteLine(person.Name);
Console.WriteLine(person.Age);
Console.WriteLine(person.Address.Street);
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
}
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
public class Program
{
public static void Main()
{
// 创建一个类实例
var myObject = new MyClass
{
Property1 = "Value1",
Property2 = 123
};
// 类对象序列化为JObject
JObject jObject = JObject.FromObject(myObject);
string json = jObject.ToString();
Console.WriteLine(json);
// JObject反序列化为类对象
MyClass newMyClass = jObject.ToObject<MyClass>();
Console.WriteLine($"Property1: {newMyClass.Property1}, Property2: {newMyClass.Property2}");
}
}
public class MyClass
{
public string Property1 { get; set; }
public int Property2 { get; set; }
}
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
}
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
// 创建一个类的实例
MyObject obj = new MyObject
{
Id = 1,
Name = "Example"
};
// 将类对象序列化为JArray
JArray jArray = JArray.FromObject(new[] { obj });
// 将JArray反序列化为类对象
MyObject deserializedObj = jArray.ToObject<MyObject[]>()[0];
// 输出反序列化结果
Console.WriteLine(deserializedObj.Id); // 输出: 1
Console.WriteLine(deserializedObj.Name); // 输出: Example