-1

I am sending data from dot net minimal 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));
});

It is showing response as following in unity:

{"contentType":null,"serializerSettings":null,"statusCode":null,"value":[4739167,4745212]}

But while parsing this data, it is failing and I am not sure what is wrong. Parsing code:

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}");
        }
 }

The values are always null. This is object model:

[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>();
}

If the above 'Value' is not initialized, it shows, object reference is not set to an instance of object, error.

I tried lowercase and CamelCase but nothing seems to make it parse successfully. On the same script I can parse other objects from another endpoint reposes. What should I do?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Rifat
  • 1,700
  • 3
  • 20
  • 51
  • Does this answer your question? [Serialize and Deserialize Json and Json Array in Unity](https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity)... In short Unity doesn't serialize properties, only fields. You can use System.Text.Json or Newtonsoft.Json if you want to maintain model consistency. – shingo Apr 07 '23 at 09:04

1 Answers1

0

I would suggest to skip unnecessary wrapping and just return the list of ids:

app.MapGet("/mytableDistinct", async ([FromServices] ShipmentDbContext dbContext) =>
{
    IQueryable<long> query = dbContext.MyTables.Select(mt => mt.ShipmentID).Distinct();

    return await query.ToListAsync();
});

And parse to List<long> on Unity side (if it supports root arrays):

var apiResponse = JsonUtility.FromJson<List<long>>(jsonResponse);

The values are always null.

I have not worked with JsonUtility.FromJson but my guess would that it is case-sensitive, so you will need to change the class to have corresponding property names (i.e. public class AllShipmentIDs{public List<int> value { get; set; }} or use 3rd party library to handle JSON).

UPD

Based on this answer you may need to do something like:

app.MapGet("/mytableDistinct", async ([FromServices] ShipmentDbContext dbContext) =>
{
    // ...
    return new {Items = await query.ToListAsync()};
});

And on the Unity side:

int[] ids = JsonHelper.FromJson<int>(jsonString);
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Thank you for answering. When I remove wrapping I get such warning in squiggly lines: `iActionResult instances should not be returned from a MapGet delegate parameter. ` And after using lowercase `value` I get same null result. – Rifat Apr 07 '23 at 09:06
  • 1
    @Rifat - please check the code in the answer carefully. You should strip `JsonResult`. It is class from MVC and should be used there. Either `return await query.ToListAsync();` or `return Results.Ok(await query.ToListAsync())`; – Guru Stron Apr 07 '23 at 09:17