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

相关推荐
mudtools7 小时前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫10 小时前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools1 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz1 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫1 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
未来之窗软件服务2 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther2 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
阿幸软件杂货间2 天前
Office转PDF转换器v1.0.py
开发语言·pdf·c#
sali-tec2 天前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#
Tiger_shl2 天前
【层面一】C#语言基础和核心语法-02(反射/委托/事件)
开发语言·c#