How to return data in JSON format from a Webapi . net

Asked

Viewed 481 times

-1

I’m making a call inside the API to return consumer data, but I would like to know how to return this data to the client in JSON format.

My controller:

[System.Web.Http.HttpGet]   
public async Task<ActionResult> GetConsumidor()
{
  ConsumidorDAO consumidor = new ConsumidorDAO();
  string dadosConsumidor = consumidor.getDados();

  return (dadosConsumidor);
}

I make a query in the database to bring up some data of a consumer such as name, surname, etc.

public string getDados()
{
  OracleCommand lOracleCommand = lOracleConnection.CreateCommand();
  String query;
  string nome = "";

  try
  {
    query = "select nome " +
      "from crd.cliente " +
      "where cpf_cgc = 'xxxxxxx'" +
      "  and empresa_origem = '367' ";

    lOracleCommand.CommandText = query;
    OracleDataReader reader = lOracleCommand.ExecuteReader();
    while (reader.Read())
    {
      nome = reader["nome"].ToString();
    }
  }
  catch (Exception lException)
  {
    _status += lException.Message + "\n";
    lOracleCommand.Connection.Close();
  }

  return nome;
}
  • The client would be what exactly? for example, you would save the data in a text file?

  • I only return the data in formed JSON with the information

1 answer

0

JSON is an object representation in Javascript format (Javascript Object Notation).
As you are returning only one string, this does not fit as an object, objects are formed by zero or more key and value pairs.

If you insist on returning one JSON, can make an object with a property that has its value as a string and serialize it in the return of API, follows an example.

Example:

//outros using
using System.Web.Script.Serialization;


public class ResultadoObjeto
{
    public string Propriedade { get; set; }
}

[System.Web.Http.HttpGet]   
public async Task<string> GetConsumidor()
{
   ConsumidorDAO consumidor = new ConsumidorDAO();
   string dadosConsumidor = consumidor.getDados();

   //aqui gero e preencho o objeto
   var resultadoObjeto = new ResultadoObjeto();
   resultadoObjeto.Propriedade = dadosConsumidor;

   //aqui o transformo em JSON e retorno
   string json = new JavaScriptSerializer().Serialize(resultadoObjeto);
   return (json);

}
  • I did as in the example but at the time of return it is not possible to convert string in System.Web.Mvc.Actionresult @Paz

  • modify Actionresult to string, edit the response to the code that will work correctly

Browser other questions tagged

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