C# Newtonsoft.Json

本文介绍如何在C# .net中实现JSON解析。

由于应用场景只需要将JSON字符串展开,并提取部分对象,所以用到的方法不多;

第一步,安装 Newtonsoft.Json

在NuGet 包管理器中,搜索并安装 Newtonsoft.Json 库;

然后添加引用;

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

JSON解析

1、初步解析,用于打印完整的JSON字符串

有些JSON格式的字符串不包含控制字符"\t""\n",手动处理起来比较麻烦;

最好还是借助于json库函数,打印转出来的字符串,便于直观查看;

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

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

2、解析K-Value

JSON解析的前提是要构建JSON 类;

参考如下;

//如下定义了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;




猜你喜欢

转载自blog.csdn.net/weixin_38743772/article/details/128654836