使用 Json.NET 将 PHP 中的 JSON 显示到 DataGridView 中






4.83/5 (4投票s)
解释如何使用 JSON 从 C# 中的远程服务器获取数据。
简介
几天前,在将托管的MySQL数据库迁移到新的主机后,我感到非常惊讶:新的主机不接受从外部连接到数据库。
这对我是个问题,因为我正在使用一个应用程序(用 C# 开发),该应用程序通过 ODBC 连接到此数据库。
我找到获取信息的方法是:创建一些 PHP 文件,这些文件托管在我的服务器上,将在本地连接到数据库并以 JSON 格式返回信息。 然后我需要更改我的 C# 应用程序以使用这些 JSON。
我想和大家分享整个过程。
Json.NET
我找到了这个很棒的框架来处理 JSON。 首先要做的是安装它,最简单的方法是 NuGet。 为此,请打开 Visual Studio,启动程序包管理器并写入此
PM> Install-Package Newtonsoft.Json
现在我们准备好开始工作了!
MySQL 表结构
我创建了一个非常简单的表,其中包含几行。
这是我用来创建它的脚本。
CREATE TABLE 'Users' (
'Id' INT UNSIGNED NOT NULL AUTO_INCREMENT ,
'FirstName' VARCHAR( 50 ) NOT NULL ,
'LastName' VARCHAR( 50 ) NOT NULL ,
'Email' VARCHAR( 100 ) NOT NULL ,
PRIMARY KEY ( 'Id' ) ,
FULLTEXT (
'FirstName' ,
'LastName' ,
'Email'
)
) TYPE = MYISAM ;
然后,我插入了几行。 这是脚本
INSERT INTO 'Users' ('FirstName' , 'LastName' , 'Email' )
VALUES
('Pepe', 'Pardo', 'pepe.pardo@gmail.com'),
('Manolo', 'Locomia', 'manolo.locomia@gmail.com'),
('Diplo', 'Docus', 'diplo.docus@gmail.com');
PHP 脚本
下一步是创建一个 php 文件,该文件连接到数据库,执行查询并以 JSON 格式返回结果。
Foo.php
<?php
// Set your database configuration here
$DatabaseServer = "localhost";
$DatabaseUser = "testUser";
$DatabasePassword = "testPassword";
$DatabaseName = "myDBName";
// Set a connection to the database
$mysqli = new mysqli($DatabaseServer, $DatabaseUser, $DatabasePassword, $DatabaseName);
// Try to connect. Die if error
if ($mysqli->connect_errno)
{
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// Set a resultset. For testing we are goint to return the full table (3 rows)
$result = $mysqli->query("SELECT Id, FirstName, LastName, Email FROM Users;");
// Iterate the resultset to get all data
while($row = mysqli_fetch_assoc($result))
{
$rows[] = $row;
}
// Close the resultset
$result->close();
// Close the database connection
$mysqli->close();
// Returns the JSON representation of fetched data
print(json_encode($rows, JSON_NUMERIC_CHECK));
?>
请记住使用 mysqli_fetch_assoc
而不是 mysql_fetch_array
,否则会在 JSON 字符串中获得重复的值。
请注意,从 PHP 5.3.3 开始,您可以使用标志 JSON_NUMERIC_CHECK
进行自动转换数字。 我使用它是因为我希望将字段Id作为int
返回。
现在是获取 PHP 文件服务器的时候了。 如果您尝试从网络浏览器运行它,您将得到如下结果
因此,我们解决了服务器端的问题。 现在我们需要用 C# 编写应用程序来显示查询。
桌面应用程序
如上所述安装 Json.NET 后,我们就可以开始编码了。
首先,创建一个 User
类,该类将用于存储返回的每个对象。
User.cs
using Newtonsoft.Json;
namespace JsonToDataListView
{
class User
{
[JsonProperty("Id")]
public int Id { get; set; }
[JsonProperty("FirstName")]
public string Name1 { get; set; }
[JsonProperty("LastName")]
public string Name2 { get; set; }
[JsonProperty("Email")]
public string EmaiAddress { get; set; }
}
}
此类中唯一特别的是使用 JsonPropertyAttribute
将每个 JSON 键与类属性匹配。
Form1.cs
using System;
using System.Net;
using System.Windows.Forms;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace JsonToDataGridView
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
var json = wc.DownloadString(textBox1.Text);
List<User> users = JsonConvert.DeserializeObject<List<User>>(json);
dataGridView1.DataSource = users;
}
}
}
首先,我们将创建一个 WebClient
对象,使我们能够连接到我们之前创建的 PHP 页面。
然后,我们使用 DownloadString
函数将页面内容下载到变量中。 此时,我们的应用程序将拥有所有信息。 现在我们只需要使其易于阅读。 这就是 Json.NET 将帮助我们的地方。
从 JSON 反序列化创建一个 User
对象列表。 我们将使用静态类 DeserializeObject
和函数 JsonConvert
,并将从 Web 获得的完整结果作为参数传递。
现在我们只需要使用 DataSource
属性在 DataGridView
中打印数据即可。