【发布时间】:2021-05-23 09:21:16
【问题描述】:
我正在用 c# 连接到 rest api 服务器。一个json输出如下。
WindowsForms、Model和Repository文件如下。
1-) 换句话说,我想将json数据传入的“结果”对象传输到模型文件中,并在gridview上显示。
2-) 另外,当我发出“Get”请求时,我想请求一个带有参数的“Body”对象。 示例:{"business_code": "dental"}
CustomersModel.cs
namespace HastaTakip.Models
{
public class CustomersModel
{
public result _result { get; set; }
public class result
{
public int id { get; set; }
public string customer_name { get; set; }
public string customer_lastname { get; set; }
public string customer_identity { get; set; }
public string customer_gender { get; set; }
public string customer_phone { get; set; }
public string customer_description { get; set; }
public bool customer_status { get; set; }
public string doctor { get; set; }
public string customer_code { get; set; }
public string business_code { get; set; }
public int user_code_id { get; set; }
}
}
}
CustomersRepository.cs
using System.Net.Http;
using System;
using System.Threading.Tasks;
using HastaTakip.Models;
using Newtonsoft.Json;
namespace HastaTakip.Api
{
public class CustomersRepository
{
public HttpClient _client;
public HttpResponseMessage _response;
public CustomersRepository()
{
_client = new HttpClient();
_client.BaseAddress = new Uri("http://localhost:3000/");
_client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<CustomersModel> GetList()
{
_response = await _client.GetAsync($"customers");
var json = await _response.Content.ReadAsStringAsync();
var listCS = JsonConvert.DeserializeObject<CustomersModel>(json);
return listCS;
}
}
}
WindowsForms.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HastaTakip.Api;
using HastaTakip.Models;
namespace HastaTakip.Forms
{
public partial class frmCustomerList : Form
{
CustomersRepository _repository = new CustomersRepository();
public frmCustomerList()
{
InitializeComponent();
LoadData();
}
private async void LoadData()
{
var listCS = await _repository.GetList();
gridControl1.DataSource = listCS;
}
private void frmCustomerList_Load(object sender, EventArgs e)
{
}
}
}
Json 结果
{
"result": [
{
"id": 1,
"customer_name": "Test1",
"customer_lastname": null,
"customer_identity": "54sd45",
"customer_gender": "Man",
"customer_phone": null,
"customer_description": "kkjkjk.",
"customer_status": null,
"doctor": null,
"customer_code": "bcc50586-6960-4766-9468-c9dc55780e40",
"business_code": "dental",
"user_code_id": 1
},
{
"id": 2,
"customer_name": "Depron",
"customer_lastname": null,
"customer_identity": "564434",
"customer_gender": "WOMEN",
"customer_phone": null,
"customer_description": "record test.",
"customer_status": null,
"doctor": null,
"customer_code": "344865b4-1028-4051-9ec4-71db17414787",
"business_code": "dental",
"user_code_id": 1
}
]
}
【问题讨论】:
标签: c# json visual-studio rest