Rest exception: Unable to find a constructor to us

2019-07-23 19:14发布

问题:

I know this question has been asked before, but I can't find an answer to solve this problem.

I'm making a request to a web service which returns a json, and then I save that json as an object in a list using json.net.

List<myclass> result;
var request = new RestRequest(url, Method.POST);
//Set the parameters of the request
//[...]
IRestResponse response = client.Execute(request)
Console.WriteLine(response.Content);
//response.Content = [{"nomPrecio":"string","nomPrecioEN":"string","IDrangoPrecio":0,"IDPoblacionMv":0,"NumOfertas":0,"NumOVotaciones":0,"Imagen":"anUrl"}]
//Everything works fine until here, and I can see the json is being received OK, but then...
result = JsonConvert.DeserializeObject<List<myclass>>(response.Content);

Then the console shows this message:

Rest Exception: Unable to find a constructor to use for type mynamespace.myclass. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path '[0].nomPrecio', line 1, position 14.

namespace mynamespace
{
    public class myclass
    {
        public myclass()
        {
        }
        public myclass(string nomPrecio, string nomPrecioEN, int IDrangoPrecio, int IDPoblacionMv, int NumOfertas, int NumOVotaciones, string Imagen)
        {
            this.nomPrecio = nomPrecio;
            this.nomPrecioEN = nomPrecioEN;
            this.IDrangoPrecio = IDrangoPrecio;
            this.IDPoblacionMv = IDPoblacionMv;
            this.NumOfertas = NumOfertas;
            this.NumOVotaciones = NumOVotaciones;
            this.Imagen = Imagen;
        }
        public string nomPrecio { get; set; }
        public string nomPrecioEN { get; set; }
        public int IDrangoPrecio { get; set; }
        public int IDPoblacionMv { get; set; }
        public int NumOfertas { get; set; }
        public int NumOVotaciones { get; set; }
        public string Imagen { get; set; }
    }
}

What's more weird is that I make the same for other classes in the app and no one returns this error, all of them works.

I tried a lot of things like "json2csharp" but nothing works.

Any tip about what could I be doing wrong? Thanks

回答1:

Some linker problem mb? Try to add for your class

[Preserve(AllMembers = true)] 

That can happen when linker is set to "Sdk and user assemblies"