C# 调用接口处理返回json数据

项目中处理json需要使用Newtonsoft,访问接口使用RestSharp,先将这两个库添加项目引用,在文件头部进行引用

using Newtonsoft.Json;

using Newtonsoft.Json.Linq;

using RestSharp;

方式一:按数组解析

InfoModel info = new InfoModel();

string hostV = ins.Host;

string urlV = ins.Url;

string stationNameV = ins.StationName;

var client = new RestClient(hostV);

string url = hostV + urlV + stationNameV;

var request = new RestRequest( url , Method.POST);

request.AddHeader("Content-Type", "application/json");

var response = client.Execute(request);

JObject jo = (JObject)JsonConvert.DeserializeObject(response.Content);

string success = jo["success"].ToString();

string msg = jo["msg"].ToString();

string name = jo["name"].ToString();

string tempreture = jo["tempreture"].ToString();

string humidity = jo["humidity"].ToString();

string inputTime = jo["inputTime"].ToString();

info.Success = success;

info.Msg = msg;

if (info.Success == "true")

{

info.Tempreture = tempreture;

// MessageBox.Show(tempreture);

}

方式二:映射转换类

定义类模型InfoModel

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace monitorFlowworkAndSubmit.Model

{

public class InfoModel

{

private string _success;

private string _msg;

private string _id;

private string _stationName ;

private string _tempreture ;

private string _humidity ;

private string _inputTime;

public string Success

{

get { return _success; }

set { _success = value; }

}

public string Msg

{

get { return _msg; }

set { _msg = value; }

}

public string Id

{

get { return _id; }

set { _id = value; }

}

public string StationName

{

get { return _stationName; }

set { _stationName = value; }

}

public string Tempreture

{

get { return _tempreture; }

set { _tempreture = value; }

}

public string Humidity

{

get { return _humidity; }

set { _humidity = value; }

}

public string InputTime

{

get { return _inputTime; }

set { _inputTime = value; }

}

}

}

获取及转换代码

InfoModel info = new InfoModel();

string hostV = ins.Host;

string urlV = ins.Url;

string stationNameV = ins.StationName;

var client = new RestClient(hostV);

string url = hostV + urlV + stationNameV;

var request = new RestRequest( url , Method.POST);

request.AddHeader("Content-Type", "application/json");

var response = client.Execute(request);

info = JsonConvert.DeserializeObject<InfoModel>(response.Content);

相关推荐
小老鼠爱大米2 小时前
[C#] WPF - 资源URI
c#·wpf·uri
阿蒙Amon9 天前
《C#图解教程 第5版》深度推荐
开发语言·c#
暖馒9 天前
C#委托与事件的区别
开发语言·c#
JosieBook10 天前
【C#】C#异步编程:异步延时 vs 阻塞延时深度对比
c#·多线程·异步·阻塞
甄天10 天前
WPF中MVVM和MVVMLight模式
c#·wpf·visual studio
冰茶_10 天前
ASP.NET Core API文档与测试实战指南
后端·学习·http·ui·c#·asp.net
奔跑的蜗牛AZ10 天前
TiDB 字符串行转列与 JSON 数据查询优化知识笔记
笔记·json·tidb
_oP_i10 天前
实现 “WebView2 获取word选中内容
开发语言·c#·word
Kookoos10 天前
ABP vNext + Azure Application Insights:APM 监控与性能诊断最佳实践
后端·c#·.net·abp vnext
专注VB编程开发20年10 天前
asp.net core Razor动态语言编程代替asp.net .aspx更高级吗?
开发语言·后端·c#·asp.net·.net