4

I'm having issues with .net core 3.0 when I convert a struct to a json. (with wasn't a problem when I was using .net core 2.2)

This is my struct

[Serializable]
struct Item
{
   public int A;
   public string B;
   public int C;
   public decimal D;
   public decimal E;
}

This is my code

var linhas = COD_PRODUTO.Count;
Item[] item = new Item[linhas];

for (int cont = 0; cont < linhas; cont++)
{
   DESCRICAO = _context.Produtos.Where(c => c.COD_PRODUTO == COD_PRODUTO[cont]).Select(c => 
   c.DESCRICAO).Single().ToString();

   item[cont].A = COD_PRODUTO[cont];
   item[cont].B = DESCRICAO;
   item[cont].C = QUANTIDADE[cont];
   item[cont].D = PRECOUNITARIO[cont];
   item[cont].E = TOTAL[cont];
}

var json = JsonSerializer.Serialize(item); //3.0
Debug.WriteLine("----------------------" + json);

return new JsonResult(json);

It's returning me empty values, any help?

1 Answer 1

5

As of 3.0, ASP.NET Core uses the System.Text.Json to serialize/deserialize json. And the public properties are serialized by default. See official docs:

Serialization behavior

By default, all public properties are serialized.

  1. To fix that issue, you could change those public fields to public properties as below:

    [Serializable]
    struct Item
    {
        public int A {get;set;}
        public string B {get;set;}
        public int C {get;set;}
        public decimal D {get;set;}
        public decimal E {get;set;}
    }
    
  2. Or as an alternative, you can follow the official docs to fallback to the old behavior by using the Newtonsoft.Json package:

    services.AddControllers()
        .AddNewtonsoftJson(opts =>{ /*...*/ });
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.