Error consuming web service with ajax (JSON) in Cordova app

Asked

Viewed 77 times

-3

Good evening I built a web servisse where there is a method that receives a string parameter, which I use to serialize to a class as follows:

/*parte da classe cliente*/
public  class Cliente
    {
        public string Codigo { get; set; }
        public string  Descricao { get; set; }
        public string DataNascimento { get; set; }
        public int Sexo { get; set; }
        public string Endereco { get; set; }
        public string Bairro { get; set; }
        public string Telefone { get; set; }
     }

Here the method in Ws that receives and deserializes() the json for the above class:

 public string  InsereCliente(string Cliente)
    {      
        string resultado = string.Empty;
        try
        {
            Util.GravaErroLog(Cliente, "Teste para ver se a string esta chegando");
            List<string> Rec = new List<string>();
            SerializadorDAO dao = new SerializadorDAO();
            var Cli = dao.DesSerializarUnitario(Cliente);//dao.DeSerializarJson<List<Cliente>>(Cliente);
            Rec.Add(Util.InsereCliente(Cli));
            resultado = dao.SerializaDadosJson<string>(Rec);
        }
        catch( Exception ex)
        {
            Util.GravaErroLog(ex.Message, "InsereCliente");
        }


        return resultado;
    }

Here the q method performs the process of deserialization (actually I tried in two ways but only runs in the local test if required via ajax of the error that I show forward).

/*Primeiro teste*/
public string  InsereCliente(string Cliente)
    {      
        string resultado = string.Empty;
        try
        {
            Util.GravaErroLog(Cliente, "Teste para ver se a string esta chegando");
            List<string> Rec = new List<string>();
            SerializadorDAO dao = new SerializadorDAO();
            var Cli = dao.DesSerializarUnitario(Cliente);//dao.DeSerializarJson<List<Cliente>>(Cliente);
            Rec.Add(Util.InsereCliente(Cli));
            resultado = dao.SerializaDadosJson<string>(Rec);
        }
        catch( Exception ex)
        {
            Util.GravaErroLog(ex.Message, "InsereCliente");
        }


        return resultado;
    }

Here is another method of deserialization but using lists

/* 2 Teste */

public List<T>DeSerializarJson <T>(string json) {
  var Lista=new List<T>();
  try {
    DataContractJsonSerializer ser=new DataContractJsonSerializer(typeof(List<T>));
    using (MemoryStream ms=new MemoryStream(Encoding.UTF8.GetBytes(json))) {
      Lista=(List<T>)ser.ReadObject(ms);
    }
    ;
  }
  catch(Exception ex) {
    GravaErroLog(ex.Message, "DeserializarJson");
  }
  return Lista;
}

here the client part in the first Cordova populates the object:

var Cliente;

function PopulaClienteJson() {
  var D = $('#DataNasc').val().split('-');
  var data = '';
  var dia = D[2]
  var mes = D[1];
  var Ano = D[0];
  data = mes + '/' + dia + '/' + Ano;
  Cliente = [{
    Descricao: new String($('#descricao').val()),
    Endereco: new String($('#Endereco').val()),
    DataNascimento: new String(data),
    Numero: new String($('#Numero').val()),
    Bairro: new String($('#Bairro').val()),
    Cidade: new String($('#Cidade').val()),
    Cep: new String($('#Cep').val()),
    Email: new String($('#Email').val()),
    RG: new String($('#RG').val()),
    CPF: new String($('#CPF').val()),
    Profissao: new String($('#Profissao').val()),
    ComoConheceu: new String($('#Info').val())
  }]

}

then the call Ajax

var UrlPadrao = "http://192.168.2.42/WebUltra/webOrcs.asmx/InsereCliente";

function EnviaCliente() {

  var json1 = JSON.stringify(Cliente);
  alert(json1);
  $.ajax({
    type: "POST",
    url: UrlPadrao,
    data: json1,
    contentType: 'application/json; charset=utf-8',
    datatype: "json",
    success: function(data) {
      PopulaCodigoCliente(data)
    },
    error: function(data) {
      erroJson(data)
    }
  });

and finally the mistake :

"{"Message":"O tipo 'System.Collections.Generic.IDictionary`2
    [
      [System.String, mscorlib, Version=4.0.0.0, Culture=neutral,  PublicKeyToken=b77a5c561934e089],
      [System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]
    ]' não é suportado para desserialização de uma matriz.",
  "StackTrace":"   
      em System.Web.Script.Serialization.ObjectConverter.ConvertListToObject(IList list, Type type, JavaScriptSerializer serializer, Boolean throwOnError, IList& convertedList)
      em System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)
      em System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
      em System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)
      em System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}"

there was almost forgetting the result of creating json

[ 
    {
        "Codigo":"0", 
        "Descricao":"wdadeqwdqwe", 
        "Endereco":"aa", 
        "DataNascimento":"2009-01-01", 
        "Numero":"3", 
        "Bairro":"aa",  
        "Cidade":"aaa", 
        "Cep":"33", 
        "Email":"a", 
        "RG":"33", 
        "CPF":"33", 
        "Profissao":"aa", 
        "ComoConheceu":"aa"
    }
]

then if I go in the browser and call the method and pass the parameter it inserts normal, but in the call via the error ajax. By either?

1 answer

0

The solution to this question was as follows: I had to make the correction of the parameter that was being sent by the ajax call that follows:

function EnviaCliente() {

  var json1 = JSON.stringify(Cliente);
  alert(json1);
  $.ajax({
    type: "POST",
    url: UrlPadrao,
    data: json1,
    contentType: 'application/json; charset=utf-8',
    datatype: "json",
    success: function(data) {
      PopulaCodigoCliente(data)
    },
    error: function(data) {
      erroJson(data)
    }
  });

for this model that respects the name of the WS parameter and the type of data that must be passed by the parameter in the Ajax call:

function EnviaCliente() {
   
    var json1 = JSON.stringify(Cliente);
    alert(json1);
    $.ajax({
        type: "POST",
        url: UrlPadrao,
        data: '{Cliente:"Teste de envio"}',//aqui a correcao 
        contentType: 'application/json; charset=utf-8',
        datatype: "json",
        async: true,
        success: function (data) { PopulaCodigoCliente(data) },
        error: function (data) { erroJson(data) }
    });

I will now quantify the parameters of the Json1 object and describe them in Ws so that you can finally use this object. Thanks "for the help"

Browser other questions tagged

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