【发布时间】:2016-07-28 16:47:49
【问题描述】:
我正在使用 Xamarin.forms 做一个跨平台应用程序,我需要从 MySql 服务器检索数据。通过我的研究,我发现使用 MySqlClient 库并不安全,因此我在我的数据库和应用程序之间使用 Web 服务层进行了搜索。
此代码对 MySql 数据库进行查询,以数组的形式输出结果并以 JSON 编码回显它们。这是PHP代码:
<?php
$servername = "adress";
$username = "client";
$password = "";
$dbname = "dnName";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT text1, text2 FROM tblTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$items = array();
// output data of each row
while($row = $result->fetch_assoc()) {
$item = array("Texte1" => $row['text1'],
"Texte2" => $row['text2']);
array_push($items, $item);
}
echo json_encode($items);
} else {
echo "0 results";
}
$conn->close();
?>
此代码调用一个 PHP 文件,获取响应并将它们转换为项目列表。这是 C# 代码:
using System.Net.Http;
using Newtonsoft.Json;
//....
private Uri uri;
private HttpClient client;
private List<Items> item;
public async Task<List<Items>> ReadData()
{
client = new HttpClient();
uri = new Uri("http://adress/getdata.php");
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
item = JsonConvert.DeserializeObject<List<Items>>(content);
}
return item;
}
public class Items
{
public string text1 { get; set;}
public string text2 { get; set;}
}
所以现在,ReadData 方法的返回类型是 List<Items>,但我怎样才能在 List<string> 或简单的字符串中返回它们?
【问题讨论】:
-
预期字符串的格式是什么?
-
@MatiasCicero 也许就像我在没有 C# 代码的情况下运行它时的 PHP 代码输出:[{"Texte1":"sometext","Texte2":"anothertext"}]
标签: c# php mysql xamarin.forms