Change in json File Format

Asked

Viewed 115 times

2

My file is coming in this format, but I would like it not to appear this #id information before sale:

{
  "$id": "1", //como não mostra isso?
  "venda": [
    {
      "$id": "2",
      "poule": 73,
      "idusuario": 4,
      "vendedor": "ITAMAR SOUZA",
      "total": 50.00,
      "datajogo": "2016-01-19T00:00:00",
      "terminal": "(11)985590116",
      "empresa": "SANTIAGO - LOJA 01",
      "nsu": 73
    }
  ]
}

Code that is generating Json:

        [HttpGet]
        [Route("consulta/ListarUltimoJogosRalizado/{idusuario}")]
        public HttpResponseMessage ListarTodosJogosAtivos(int idusuario)
        {
            try
            {
                var tTabela = new  JogoAplicacao();
                var listar = tTabela.ListarPoId(idusuario);
                return Request.CreateResponse( HttpStatusCode.OK,  new { venda = listar.ToArray() } );
            }
            catch (Exception ex)
            {

                return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
            }
        }
  • Do you want to remove that in Javascript? you can do delete obj.$id, but it would be better to do it on the server

2 answers

1

Add the code snippet below to your file WebApiConfig.cs:

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

-1

There is a widely used method which is the use of Viewmodels.

You create a Viewmodel for each custom return of your API actions.

Ex:

public class VendaViewModel
{
    public int Id { get; set; }
    public int Poule { get; set; }
    public int IdUsuario { get; set; }
    public string Vendedor { get; set; }
    public decimal Total { get; set; }
    public DateTime DataJogo { get; set; }
    public string Terminal { get; set; }
    public string Empresa { get; set; }
    public int NSU { get; set; }

    public VendaViewModel ToViewModel(Venda venda)
    {
        // Recomendo refatorar com uso de AutoMapper: http://automapper.org/
        return new VendaViewModel 
        {
            Id = venda.id,
            Poule = venda.Poule,
            IdUsuario = venda.IdUsuario,            
            Vendedor = venda.Vendedor,
            Total = venda.Total,
            DataJogo = venda.DataJogo,
            Terminal = venda.Terminal,
            Empresa = venda.Empresa,
            NSU = venda.NSU
        };
    }
}

And in its action:

// ...
var listar = tTabela.ListarPoId(idusuario);
return lista.Select(Venda.ToViewModel);

This way, you can customize what will actually be delivered to the client. Even vc can filter fields that are not interesting, reducing traffic, and also format output, for example, from Total, using regional settings.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.