我正在从。net最小API发送数据:
app.MapGet("/mytableDistinct", async ([FromServices] ShipmentDbContext dbContext) =>
{
IQueryable<long> query = dbContext.MyTables.Select(mt => mt.ShipmentID).Distinct();
var shipmentIDs = await query.ToListAsync();
return Results.Ok(new JsonResult(shipmentIDs));
});
显示的响应一致如下:
{"contentType":null,"serializerSettings":null,"statusCode":null,"value":[4739167,4745212]}
但是在解析这些数据时,它失败了,我不确定是什么错了。解析代码:
var request = UnityWebRequest.Get(url);
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
if (request.result == UnityWebRequest.Result.Success)
{
//var jsonResponse = request.downloadHandler.text;
//var apiResponse = JsonUtility.FromJson<AllShipmentIDs>(jsonResponse);
try
{
var jsonResponse = request.downloadHandler.text;
Debug.Log(jsonResponse);
var apiResponse = JsonUtility.FromJson<AllShipmentIDs>(jsonResponse);
List<int> shipmentIDs = apiResponse.Value;
Debug.Log("Shipment IDs: " + string.Join(",", shipmentIDs));
}
catch (Exception ex)
{
Debug.LogError($"Failed to deserialize API response: {ex.Message}");
}
}
值总是null。这是对象模型:
[System.Serializable]
public class AllShipmentIDs
{
public string ContentType { get; set; }
public object SerializerSettings { get; set; }
public int? StatusCode { get; set; }
public List<int> Value { get; set; } = new List<int>();
}
如果上面的'Value'没有初始化,它显示,对象引用没有设置为对象的实例,错误。
我尝试了小写和CamelCase,但似乎没有使其解析成功。在同一个脚本上,我可以解析来自另一个端点的其他对象。我该怎么办?
我建议跳过不必要的换行,只返回id列表:
app.MapGet("/mytableDistinct", async ([FromServices] ShipmentDbContext dbContext) =>
{
IQueryable<long> query = dbContext.MyTables.Select(mt => mt.ShipmentID).Distinct();
return await query.ToListAsync();
});
在Unity端解析List<long>
(如果它支持根数组):
var apiResponse = JsonUtility.FromJson<List<long>>(jsonResponse);
值总是null
我没有使用JsonUtility.FromJson
,但我猜它是区分大小写的,所以你需要更改类以具有相应的属性名称(即public class AllShipmentIDs{public List<int> value { get; set; }}
或使用第三方库来处理JSON)。
乌利希期刊指南
根据这个答案,你可能需要做如下的事情:
app.MapGet("/mytableDistinct", async ([FromServices] ShipmentDbContext dbContext) =>
{
// ...
return new {Items = await query.ToListAsync()};
});
在Unity端:
int[] ids = JsonHelper.FromJson<int>(jsonString);