Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 345 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Fresh ASP.NET Core API returns empty JSON objects

#1
I have made a .NET Core Web API project to test it out.

My problem is, that the API returns an empty JSON object, when I request the endpoint, which is located at "/api/cars/123" for instance. This happens no matter what kind of object I put in, unless it's any primitive datatype, or an array thereof. The response is always:

{}


The configuration of the application is completely default, on a fresh Visual Studio 2017 installation.

I have the following classes:

**Car.cs**

namespace Ex6.Entities
{
public class Car
{
private int Id { get; set; }
private string Make { get; set; }
private string Model { get; set; }

public Car(int Id, string Make, string Model)
{
this.Id = Id;
this.Make = Make;
this.Model = Model;
}
}
}

**CarsController.cs:**

using Microsoft.AspNetCore.Mvc;
using Ex6.Entities;

namespace Ex6.Controllers
{
[Route("api/[controller]")]
public class CarsController : Controller
{

[HttpGet("{id}")]
public JsonResult GetCar(int id)
{
return Json(new Car(1, "Toyota", "Aygo" ));
}

}
}

Am I missing something?
Reply

#2
In order for the JsonSerializer to be able to see and serialize your properties, they need to be public:

public int Id { get; private set; } //the setters can be private
public string Make { get; set; }
public string Model { get; set; }
Reply

#3
Try this by adding configure

services.AddControllersWithViews().AddNewtonsoftJson();

....AddNewtonsoftJson() this should solve the issue.
Reply

#4
For some reason, Text.JSON doesn't serialize public fields as well, so they need to be properties. This solved the similar issue for me
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through