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

相关推荐
pchmi1 小时前
C# OpenCV机器视觉:红外体温检测
人工智能·数码相机·opencv·计算机视觉·c#·机器视觉·opencvsharp
Bro_cat2 小时前
深入浅出JSON:数据交换的轻量级解决方案
java·ajax·java-ee·json
m0_748248022 小时前
【MySQL】C# 连接MySQL
数据库·mysql·c#
oulaqiao5 小时前
语言集成查询LINQ
c#·linq
xcLeigh6 小时前
WPF实战案例 | C# WPF实现大学选课系统
开发语言·c#·wpf
one9966 小时前
.net 项目引用与 .NET Framework 项目引用之间的区别和相同
c#·.net·wpf
xcLeigh6 小时前
WPF基础 | WPF 布局系统深度剖析:从 Grid 到 StackPanel
c#·wpf
军训猫猫头16 小时前
52.this.DataContext = new UserViewModel(); C#例子 WPF例子
开发语言·c#·wpf
AI+程序员在路上20 小时前
C#调用c++dll的两种方法(静态方法和动态方法)
c++·microsoft·c#