Scenes
Use Newtonsoft.Json in C# to parse Json strings:
The parsing of JSON strings mentioned above is actually the deserialization of JSON objects.
When interacting with third parties, it is often necessary to encapsulate objects, store various attribute messages, and then
The object is serialized into a json string and sent for transmission.
Note:
Blog:
Domineering Rogue Temperament_C#, Architecture Road, SpringBoot-CSDN Blog
accomplish
1. Directly go to Solution Explorer-Reference-Manage Nugut Packages-Search in Browse
Newtonsoft.Json to install
2. Encapsulation object
/// <summary>
/// api 状态
/// </summary>
class ApiState
{
//连通状态
public int connectState { get; set; }
//连通状态监测时间
public string connectStateMonitorTime { get; set; }
//服务状态
public int serviceState { get; set; }
//服务状态监测时间
public string serviceStateMonitorTime { get; set; }
}
3. Object assignment
ApiState apiState = new ApiState();
apiState.connectState = 0;
apiState.connectStateMonitorTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
apiState.serviceState = 0;
apiState.serviceStateMonitorTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
4. Serialize the object as a json string
string json1 = JsonConvert.SerializeObject(apiState);
Console.WriteLine(json1);
5. Deserialize json string into object
//{"connectState":0,"connectStateMonitorTime":"2023-09-22 15:36:13","serviceState":0,"serviceStateMonitorTime":"2023-09-22 15:36:13"}
ApiState apiState2 = JsonConvert.DeserializeObject<ApiState>(json1);
Console.WriteLine(apiState2.connectState+apiState2.connectStateMonitorTime);