猿问

将多个列表合并为一个 json 字符串

我需要通过 json 将数据从我的游戏服务器发送到客户端,并从数据库中获取大量数据并发送它会产生问题


目前我正在调用数据库以获取数据时创建多个列表,现在我被卡住了,因为我有数据但在多个列表中,我不知道如何返回数据。


我觉得我应该在这里将它转换为 JSON,然后返回 json 字符串,但这一切真的很混乱


public static void GetLobbyList() {

        string query = "SELECT * FROM que";


        MySqlCommand cmd = new MySqlCommand(query, MySQL.mySQLSettings.connection);

        MySqlDataReader reader = cmd.ExecuteReader();


        List<int> ids = new List<int>();

        List<string> uids = new List<string>();

        List<int> bets = new List<int>();

        List<string> games = new List<string>();


        while (reader.Read()) {

            ids.Add((int)reader["id"]);

            uids.Add((string)reader["uid"]);

            bets.Add((int)reader["bet"]);

            games.Add((string)reader["game"]);

        }


        reader.Close();


    }

所以在这里我从数据库中读取信息,由于缺乏经验,我将每个数据点添加到列表中(这真的很难看,我知道必须有更好的方法)


所以基本上我Grab the data->Parse to json->Send string to client


如果可以假设返回的数据来自一个表


编号 | uid | 打赌 | 游戏


我想在 json 中返回一个数组,看起来像


{ {“id”:1,“uid”:“erjfh4982y9hf”,“赌注”:3,“游戏”:“贪吃蛇”} {“id”:2,“uid”:“gsegt34t”,“赌注”:2 , "游戏" : "贪吃蛇" } }


我不太熟悉 json 及其工作原理,但我知道这是将大数据包从我的服务器发送到我的客户端的唯一方法,因为在发送之前所有内容都必须转换为字节,而我的框架不会支持将列表转换为字节


HUWWW
浏览 185回答 2
2回答

猛跑小猪

为了实现您的目标,您应该创建一个类来保存您从数据库中检索到的数据。在我的例子中,我调用了它GameObject,它的定义如下。public class GameObject{&nbsp; &nbsp; public int Id { get; set; }&nbsp; &nbsp; public string Uid { get; set; }&nbsp; &nbsp; public int Bet { get; set; }&nbsp; &nbsp; public string Game { get; set; }}从数据库中检索信息后,您需要运行类似于以下的代码。var items = new List<GameObject>();while (reader.Read()){&nbsp; &nbsp; items.Add(new GameObject&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Id = (int)reader["id"],&nbsp; &nbsp; &nbsp; &nbsp; Uid = (string)reader["uid"],&nbsp; &nbsp; &nbsp; &nbsp; Bet = (int)reader["bet"],&nbsp; &nbsp; &nbsp; &nbsp; Game = (string)reader["game"]&nbsp; &nbsp; });}// Return the jsonPacket which will contain all the items in json format.var jsonPacket = JsonConvert.SerializeObject(items);为了使其正常工作,您需要从 nuget 中引用 Newtonsoft.Json 库。打开你的包管理器控制台并输入以下命令:Install-Package Newtonsoft.Json它会为你设置它。在我们代码的顶部,您需要using Newtonsoft.Json;能够使用库中的类来序列化为 Json。在接收端,您可以将字符串传递给JsonConvert.DeserializeObject<T>(),您将取回对象列表。

茅侃侃

您可以使用objects 和匿名类型的列表。还有一个 JSON 序列化程序,System.Web.Script.Serialization.JavaScriptSerializer如果您将System.Web.Extensions程序集添加到您的引用中,则包含该序列化程序。List<object> list = new List<object>();while (reader.Read()) {&nbsp; &nbsp; list.Add(new { id =&nbsp; (int)reader["id"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;uid = (string)reader["uid"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;bet = (int)reader["bet"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;game = (string)reader["game"], });}string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(list);
随时随地看视频慕课网APP
我要回答