Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Api json response $id variable

in asp web api i have this controller that respond to ajax request and send back json data:

public IEnumerable<PersonaleDTO> GetPersonale()
{
    var n = (from p in db.Personale
             select new PersonaleDTO { Id = p.Id, Nome = p.Nome, Cognome = p.Cognome Cellulare = p.Cellulare, Email = p.Email, Attivo = (bool)p.Attivo }).ToList();
    return n;
}

This method return seven object and it's correct.

Now when i receive back the data in the json format i see that i receive also and $id member along with the id, Nome, Cognome...

What is the $id variable? How can remove this from the json response?

like image 362
Tom Avatar asked Apr 18 '14 10:04

Tom


People also ask

Is there any standard for JSON API response format?

Yes there are a couple of standards (albeit some liberties on the definition of standard) that have emerged: JSON API - JSON API covers creating and updating resources as well, not just responses. JSend - Simple and probably what you are already doing.

How do I return a response in .NET core API?

IActionResult Return Type in ASP.NET Core Web API: The IActionResult is an interface and it is used to return multiple types of data. For example, if you want to return NotFound, OK, Redirect, etc. data from your action method then you need to use IActionResult as the return type from your action method.


1 Answers

Try this code in WebApiConfig

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;

Edit : If for some reason you're using a custom ContractResolver then as per this post

The custom ContractResolver setting overrides the PreserveReferencesHandling setting.

In your implementation of DefaultContractResolver/IContractResolver, add this;

public override JsonContract ResolveContract(Type type) {
    var contract = base.ResolveContract(type);
    contract.IsReference = false;
    return contract;
}

This behaves similarly to the PreserveReferencesHandling.None setting without a custom ContractResolver.

like image 110
Nilesh Gajare Avatar answered Sep 21 '22 00:09

Nilesh Gajare