LitJson 是輕量級 .NET JSON 函式庫,API 簡潔。本文示範定義對應類別、以 JsonMapper.ToObject 將 JSON 字串直接轉為強型別 List<T>。
public class JsonResponse
{
public string result { get; set; }
public List<GameData> info { get; set; }
}
public class GameData
{
public int ID { get; set; }
public string dept { get; set; }
public string sid { get; set; }
public string oldsid { get; set; }
public string userid { get; set; }
public string roleid { get; set; }
public string rolename { get; set; }
public string rolelevel { get; set; }
public string gold { get; set; }
public string money { get; set; }
public string inittime { get; set; }
public string lastlogin { get; set; }
public string querytime { get; set; }
}
string json_str = @"{""result"":""1"",""info"":[
{""sid"":""2"",""rolename"":""蒲翠柏"",""roleid"":""900001"",...},
{""sid"":""2"",""rolename"":""噗"",""roleid"":""5700001"",...}
]}";
var response = LitJson.JsonMapper.ToObject<JsonResponse>(json_str);
if (response.result == "1" && response.info != null)
{
foreach (var g in response.info)
{
Console.WriteLine($"{g.roleid} - {g.rolename} - Lv.{g.rolelevel}");
}
}
[JsonProperty("field_name")] 指定對應 (需引用 LitJson 命名空間)。DateTime.Parse。JsonData (動態物件) 再手動映射。// NuGet
Install-Package LitJson
// 或 .NET CLI
dotnet add package LitJson