C# Newtonsoft.Json

This article describes how to implement JSON parsing in C#.net.

Since the application scenario only needs to expand the JSON string and extract some objects, there are not many methods used;

The first step is to install Newtonsoft.Json

In the NuGet package manager, search and install the Newtonsoft.Json library;

Then add the reference;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

JSON parsing

1. Preliminary analysis, used to print the complete JSON string

Some strings in JSON format do not contain control characters "\t" and "\n", which is cumbersome to handle manually;

It is best to use the json library function to print the converted string for easy viewing;

//json为输入的JSON格式的字符串
JObject jsoned = JObject.Parse(json);
string json_str = jsoned.ToString();

//json_str 就是得到的完全展开的字符串
//jsoned 则是得到的Json对象

2. Analyzing K-Value

The premise of JSON parsing is to build JSON classes;

The reference is as follows;

//如下定义了JSON中2个子json对象的定义

public class test_result
{
	public string cmd;
	public string module;
	public string rsq;
}

public class InfoItem
{
	public string module;
	public string value;
}

public class device_mac
{
	public string cmd;
	public string rsq;
	public List<InfoItem> info;
}

...

//receive_data 为输入的Json字符串
string receive_data = System.Text.Encoding.Default.GetString(bytes);

//获取数组信息,并提取其中的key-value
device_mac list = JsonConvert.DeserializeObject<device_mac>(receive_data);
for (int i = 0; i < list.info.Count; i++)
{
    string type = list.info[i].module.ToString();
    string value = list.info[i].value.ToString();
}

//获取key-value
//其中key标识测试类型,value标识测试成功或失败
test_result test_item = JsonConvert.DeserializeObject<test_result>(receive_data);
string test_type = test_item.module;
string result = test_item.rsq;




Guess you like

Origin blog.csdn.net/weixin_38743772/article/details/128654836