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);

相关推荐
xiaowu0802 小时前
策略模式-不同的鸭子的案例
开发语言·c#·策略模式
敬业小码哥2 小时前
记一次:mysql的json及json数组使用组合使用
数据库·mysql·json
一键三联啊2 小时前
BSON 和 JSON 的区别
json
VisionPowerful5 小时前
九.弗洛伊德(Floyd)算法
算法·c#
ArabySide5 小时前
【C#】 资源共享和实例管理:静态类,Lazy<T>单例模式,IOC容器Singleton我们该如何选
单例模式·c#·.net core
gc_22997 小时前
C#测试调用OpenXml操作word文档的基本用法
c#·word·openxml
almighty2710 小时前
C#海康车牌识别实战指南带源码
c#·海康车牌识别·c#实现车牌识别·车牌识别源码·c#车牌识别
c#上位机13 小时前
wpf之TextBlock
c#·wpf
almighty271 天前
C# WinForm分页控件实现与使用详解
c#·winform·分页控件·c#分页·winform分页
almighty271 天前
C#实现导入CSV数据到List<T>的完整教程
c#·csv·格式转换·c#导入数据·csv数据导入