Marcelo C Fernandes Marcelo C Fernandes - 4 months ago 14
JSON Question

How receive this Json?

I have this structure..

Cliente Side <-> Web Api Front <-> Web Api Back -> DataBase

So, When my Web Api Back send me the Json , I don´t know how to get the results.

I am not showing the connection with database!

On the Web Api Front, the line

var data = response.Content.ReadAsStringAsync().Result;
gives me the Json Array with all the correct values. But I don´t know how send this to the ApiCall on the Client Side.

What do I have to put on the Return ??????

[Service calling the Web Api Front]

public class ApiCall
{
static readonly string ApiUrl = "http://Localhost:1762/api/{0}/{1}?nomePesquisa={2}&nomeMae={3}&nomePai={4}&dtNasc={5}&nrg={6}&ncpf={7}";


//buscar os dados com os parametros digitados
public async Task<T> GetResponse<T>(string controller, string method, string nomepesquisa,
string nomemae, string nomepai, string dtnasc, string nrg, string ncpf) where T : class
{
var client = new System.Net.Http.HttpClient();

//Definide o Header de resultado para JSON, para evitar que seja retornado um HTML ou XML
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var urllink = string.Format(ApiUrl, controller, method, nomepesquisa, nomemae, nomepai, dtnasc, nrg, ncpf);
var response = await client.GetAsync(urllink);

//Lê a string retornada
var JsonResult = response.Content.ReadAsStringAsync().Result;

if (typeof(T) == typeof(string))
return null;

//Converte o resultado Json para uma Classe utilizando as Libs do Newtonsoft.Json
var rootobject = JsonConvert.DeserializeObject<T>(JsonResult);
return rootobject;
}

}


[Web Api Front calling Web Api Back]

[HttpGet]
[Route("Envolvidos")]
public IEnumerable<Envolvido> GetEnvolv(string nomePesquisa, string nomeMae, string nomePai, string dtNasc
, string nRG, string nCPF)
{

DataSet lretorno = new DataSet();

using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://Localhost:1762/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

// Usage
HttpResponseMessage response = client.GetAsync("api/nomes/Envolvidos?nomePesquisa="+nomePesquisa+"&nomeMae="+nomeMae+"&nomePai="+nomePai+"&dtNasc="+dtNasc+"&nrg="+nRG+"&ncpf="+nCPF+"").Result;

if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsStringAsync().Result;
//Envolvido envolvidoResult = JsonConvert.DeserializeObject<Envolvido>(data);
return data.AsEnumerable().Select(row => new Envolvido
{

});

}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}


//return WHATTTTT?? ;

}

}


[WebApi Back]

[HttpGet]
[Route("Envolvidos")]
public IEnumerable<Envolvido> GetEnvolv(string nomePesquisa, string nomeMae, string nomePai, string dtnasc
, string nRG, string nCPF)
{

DataSet lretorno = new DataSet();

string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;

OracleDataReader reader = null;
OracleCommand cmd = new OracleCommand();
cmd.Connection = connection;
cmd = new OracleCommand("MOBILE.XAPIMANDADOMOBILE.BUSCAPOSSIVEISCANDIDATOSPF", connection);
cmd.CommandType = CommandType.StoredProcedure;

//variáveis entrada
cmd.Parameters.Add(new OracleParameter("ivnome",nomePesquisa));
cmd.Parameters.Add(new OracleParameter("ivmae", nomeMae));
cmd.Parameters.Add(new OracleParameter("ivpai", nomePai));
cmd.Parameters.Add(new OracleParameter("ivdatanasc", dtnasc));
cmd.Parameters.Add(new OracleParameter("ivrg", nRG));
cmd.Parameters.Add(new OracleParameter("icpf", nCPF));
//variáveis de saida
cmd.Parameters.Add(new OracleParameter("oretorno", OracleDbType.RefCursor)).Direction = ParameterDirection.Output;
cmd.Parameters.Add(new OracleParameter("qretorno", OracleDbType.RefCursor)).Direction = ParameterDirection.Output;

connection.Open();
cmd.ExecuteNonQuery();

reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

//CRIO A LISTA
lretorno.Load(reader, LoadOption.OverwriteChanges, "BUSCAPOSSIVEISCANDIDATOSPF");
connection.Close();
connection.Dispose();


//CARREGO O DATASET E TRANSFORMO PARA IENUMERABLE E RETORNO SEUS VALORES PRO JSON
return lretorno.Tables[0].AsEnumerable().Select(row => new Envolvido
{
SUSPID = Convert.ToInt32(row["SUSPID"]),
IVNOME = Convert.ToString(row["SUSPNOME"]),
IVMAE = Convert.ToString(row["SUSPMAE"]),
IVPAI = Convert.ToString(row["SUSPPAI"]),
IVDATANASC = Convert.ToString(row["SUSPDATANASC"]).Replace(" 00:00:00", ""),
IVRG = Convert.ToString(row["RG"]),
ICPF = Convert.ToString(row["CPF"]),
MANDADO = Convert.ToInt16(row["TEMMANDADO"]),
OCORRENCIA = Convert.ToInt16(row["TEMOCORRENCIA"]),

});


}
}

Answer

Web API Back end is returning IEnumerable<Envolvido>

When Web Api Front end calls Web Api Backend it just needs to deserialize it to something that is assignable to IEnumerable<Envolvido>, be it a List, Collection, Array...etc

//...other code removed for brevity
if (response.IsSuccessStatusCode)
{
    var data = response.Content.ReadAsAsync<List<Envolvido>>().Result;
    return data;
}
//...other code removed for brevity