C# WPF框架从http协议上获取返回的json数据及其解析json数据

2021/10/15 11:14:30

本文主要是介绍C# WPF框架从http协议上获取返回的json数据及其解析json数据,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

C# WPF框架从http协议上获取返回的json数据及其解析json数据

【大部分知识来源地,点击跳转】

在实际开发中,我们经常会使用到API,所谓API就是一个地址,我们称之为接口。然后我们通过使用C#对这个接口发送请求,服务器会接收我们的请求并返回数据,一般是XML或者json格式。

1.json数据格式

在接下来的实例中我将使用本地服务器进行演示。
接口:http://172.16.40.118:8666/getSInfraredData?dataTime=起始时间

TIPS:起始时间就是获取起始时间之后的数据信息。

格式如下:
效果图

2.获取返回的json数据

以下示例不对xmal界面进行过多的描述。新建login.xaml及其login.xaml.cs,仅用于演示。

login.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net;//http接口命名空间
using System.IO;//输入输出流命名空间

namespace SmartShoppingSystem
{
    /// <summary>
    /// login.xaml 的交互逻辑
    /// </summary>
    /// 
    public partial class login : Window
    {
        public login()
        {
            InitializeComponent();
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
        }
        private static String Api = "http://172.16.40.118:8666/getSInfraredData";

		//封装的get方法
        public static string Get(string Url)
        {
            //System.GC.Collect();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Proxy = null;
            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "application/json; charset=UTF-8";
            request.AutomaticDecompression = DecompressionMethods.GZip;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }

            return retString;
        }

        private void Login(object sender, RoutedEventArgs e)
        {
            string getData = Get(Api + "?dataTime=11:");
            MessageBox.Show(getData)
        }
    }
}

以下是post方法,可借鉴。

		//封装的post方法
		public static string Post(string Url, string Data, string Referer)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.Referer = Referer;
            byte[] bytes = Encoding.UTF8.GetBytes(Data);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bytes.Length;
            Stream myResponseStream = request.GetRequestStream();
            myResponseStream.Write(bytes, 0, bytes.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }
            return retString;
        }

3.解析json数据(反序列化)

json数据字符串如下:

{"code":0,"result":[{"SInfraredId":1,"s1":1,"s2":1,"infrared1":15,"infrared2":18,"dataTime":"12:50:06"},{"SInfraredId":2,"s1":0,"s2":1,"infrared1":22,"infrared2":8,"dataTime":"11:02:47"},{"SInfraredId":3,"s1":1,"s2":0,"infrared1":2,"infrared2":58,"dataTime":"11:03:16"},{"SInfraredId":4,"s1":0,"s2":0,"infrared1":28,"infrared2":48,"dataTime":"11:03:39"},{"SInfraredId":5,"s1":1,"s2":1,"infrared1":8,"infrared2":8,"dataTime":"11:03:55"},{"SInfraredId":6,"s1":1,"s2":1,"infrared1":12,"infrared2":12,"dataTime":"12:58:42"}]}

1.首先我们需要将该字符串转化为一个C#中的实体类,用于存放数据。

通常有两种方案:

  1. 自己手写实体类。
  2. 利用网站进行直接转换或者直接百度搜索:JSON转C#实体类。
    可以使用以下网站:http://www.bejson.com/convert/json2csharp/
public class ResultItem
{
    /// <summary>
    /// 
    /// </summary>
    public int SInfraredId { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public int s1 { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public int s2 { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public int infrared1 { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public int infrared2 { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public string dataTime { get; set; }
}
 
public class Root
{
    /// <summary>
    /// 
    /// </summary>
    public int code { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public List <ResultItem > result { get; set; }
}

2.引入Newtonsoft.Json.DLL文件

可以直接去该dll文件官方网站搜索:https://www.newtonsoft.com/json
或者直接使用博主提供的dll文件。链接:【点击跳转】

3.完整实例代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net;//http接口命名空间
using System.IO;//输入输出流命名空间
using Newtonsoft.Json;//引入json解析命名空间

namespace SmartShoppingSystem
{
    /// <summary>
    /// login.xaml 的交互逻辑
    /// </summary>
    /// 
    public partial class login : Window
    {
        public login()
        {
            InitializeComponent();
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
        }
        private static String Api = "http://172.16.40.118:8666/getSInfraredData";

        public static string Get(string Url)
        {
            //System.GC.Collect();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Proxy = null;
            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "application/json; charset=UTF-8";
            request.AutomaticDecompression = DecompressionMethods.GZip;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }

            return retString;
        }

        //实体类
        public class ResultItem
		{
  		 public int SInfraredId { get; set; }
    	 public int s1 { get; set; }
   		 public int s2 { get; set; }
         public int infrared1 { get; set; }
         public int infrared2 { get; set; }
         public string dataTime { get; set; }
		}
 
		public class Root
		{
   		 public int code { get; set; }
    	 public List <ResultItem > result { get; set; }
		}

        private void Login(object sender, RoutedEventArgs e)
        {
            string getData = Get(Api + "?dataTime=11:");
            //解析json数据包
            //传入实体类,解析json字符串。
            Root rt = JsonConvert.DeserializeObject<Root>(getData);
            MessageBox.Show(rt.code);
            //由于这个JSON字符串的 public List<ResultItem > result 是一个集合,所以我们需要遍历集合里面的所有数据
            for (int i = 0; i < rt.result.Count; i++)
            {
                MessageBox.Show("Data=" + rt.result[i].SInfraredId+ "\r\n" + rt.result[i].s1+ "\r\n" + rt.result[i].infrared1+ "\r\n" + rt.result[i].dataTime);
            }
        }
    }
}



这篇关于C# WPF框架从http协议上获取返回的json数据及其解析json数据的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程