Error Deserializando Json

1

Server code

public class TestController: ApiController
{

    public string Get()
    {

        Users user = new Users
        {
            name = "Hola",
            surname = "Mundo"
        };
        var response = JsonConvert.SerializeObject(user);
        return response;
    }
}

Client Code

        public static async void GetResponse()
    {
        HttpClient a = new HttpClient();

        var response = await a.GetStringAsync("http://localhost:57740/api/test");

        Users u = JsonConvert.DeserializeObject<Users>(response);
        Console.WriteLine(u.name);


    }

The string I get in client is:

"\"{\\"name\\":\\"Hola\\",\\"surname\\":\\"Mundo\\"}\""

I have an error when it comes to Deserialize object in client, I guess it's because I receive too many contrabarras. Am I sending the json wrong?

    
asked by jose_m 01.10.2017 в 13:53
source

1 answer

0

Web api serializes the objects to json by default so you are serializing a json that was already serialized, that's why the bars.

Try returning the object itself instead of the string:

public User GetUser()
{
  var user = new User { Name = "hola" , surname = "Mundo" };
  return user;
}

Note that if you run it through the browser, it will probably show you an object in xml format instead of json. This is for the content-type="text/html" that by default that browsers send. If you make a request with ajax, a json returns you.

    
answered by 01.10.2017 / 15:07
source