Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core 3.0 WebApi (JsonSerialize) Does not Serialize Nested Objects/All object information

I have a list of object as IEnumerable<IHit<Header>>, but .NET Core 3.0 is not emitting all information

this is when I return a single object IHit of the list obj.ElementAt(0)

{"explanation":null,"fields":null,"highlight":{},"id":"123","index":"ky","innerHits":{},"matchedQueries":[],"nested":null, "primaryTerm":null, "routing":null, "score":10.98915, "sequenceNumber":null, "sorts":[],"source":{"timeStamp":"2019-05-16T06:16:07Z", "result":"PASS","testTimeStart":"20190516141559","testTimeEnd":"20190516141607","barcode":"XXRX8762"},"type":"_doc","version":0}

but when I return the list itself:

[{"explanation":null,"fields":null,"highlight":{},"innerHits":{},"matchedQueries":[],"nested":null,"score":10.98915,"sorts":[]}]

also when I try explicitly to call JsonSerializer

string s = JsonSerializer.Serialize(result, typeof(IEnumerable<IHit<Header>>), obj);

To Wrap Up:

  1. WebApi is working correctly and returning the object serialized correctly if a signle object:

    public IHit<Header> Get(string id)

but when a list, then it is not.

public IEnumerable<IHit<Header>> GetAll()

I tried IEnumerable, IList, List and all the same result!

  1. JsonSerializer is working neither with a single object nor with a list
like image 487
Abdulkarim Kanaan Avatar asked Sep 27 '19 03:09

Abdulkarim Kanaan


2 Answers

I still don't know the weird behavior I faced due to emitting a single object while not the case of list.

but here how solved the problem based on @poke's answer and @NeilMacMullen's comment

  1. add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
  2. in Startup.cs, add

    services.AddControllers().AddNewtonsoftJson();

like image 87
Abdulkarim Kanaan Avatar answered Nov 15 '22 00:11

Abdulkarim Kanaan


If your are using Newtonsoft.Json then do as follows:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddMvc()
        .AddJsonOptions(
            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        );

    ...
}

If you are not using Newtonsoft.Json then do as follows:

public void ConfigureServices(IServiceCollection services)
{
    ...

   services.AddMvc().AddJsonOptions(option => option.JsonSerializerOptions.MaxDepth = 2);

    ...
}

For more details : Related data and serializatione

like image 44
TanvirArjel Avatar answered Nov 14 '22 23:11

TanvirArjel