Is it possible to change the json file format?

Asked

Viewed 50 times

0

I have a code that generates me a Json file in this format:

[
  {
    "$id": "1",
    "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
  }
]

I’d like to write the exit this way:

{
"venda":
[
  {
    "$id": "1",
    "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
  }
 ]
}

This is the code:

        [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, listar.ToArray());
            }
            catch (Exception ex)
            {

                return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
            }
        }

If the code is changed to :

return Request.CreateResponse(HttpStatusCode.OK, new  { jogo = listar.ToArray() });

the return stays like this:

{
  "$id": "1",
  "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
    }
  ]
}

1 answer

1


Follows a solution:

return Request.CreateResponse(HttpStatusCode.OK, new { $id = 1, venda = listar.ToArray() } );

PS: Posted from the cell phone so I can’t test the syntax but that’s basically it

  • very valid help, see that the $id of Json repeats and changes the number, is correct like this or has another way to do?

  • updated the response

  • I appreciate the help, but my idea was to remove this $id that appears before sale : in my question see how it looks right at the end of it

  • add the following had on your webapi.config.cs : var json = config.Formatters.Jsonformatter; json.SerializerSettings.Preservereferenceshandling = Newtonsoft.Json.Preservereferenceshandling.None;

  • Great answer! Immensely grateful!

Browser other questions tagged

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