Format JSON wrong web api

Asked

Viewed 570 times

1

I’m having trouble returning json to my mvc 5 api.

In the Get method it returns a string in this format:

public string Get()
        {
           return "{\"data\":[{\"Codigo\":\"AAAA\",\"Finalidade\":\"AAAA\"},{\"Codigo\":\"AAAA\",\"Finalidade\":\"AAAA\"}]}"
}

When I ask on my page localhost:9640/api/apiimovel?formato=json look at the format:

"{\"data\":[{\"Codigo\":\"AAAA\",\"Finalidade\":\"AAAA\"},{\"Codigo\":\"AAAA\",\"Finalidade\":\"AAAA\"}]}"

But when I do this query by the normal controller json returns correct !!

What happens to this problem ?

  • You mean when you access localhost:9640/api/apiimovel?formato=json, the bars come in the string? In C# you send "aa\"bb", and on the other side, instead of receiving aa"bb, you’re getting aa\"bb?

  • I believe that you do not understand very well the concept of web.api. Please read this link and it may help you a lot: http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api

1 answer

2

The purpose of the webapi is that you return the strongly typed result and the API takes care of giving the parse to the JSON (or XML) format. The way you are doing is by returning a JSON from a string and not the json from your object.

Create a class with the Code and Purpose properties, fill in the instantiated array with your data, and return from the function:

API:

public Lista Get() {
    var result = new Lista {
        data = new[] {
            new Item {Codigo = "AAA", Finalidade = "AAAAAAA"},
            new Item {Codigo = "AAA", Finalidade = "AAAAAAA"}
        }
    };

    return result;
}

Classes:

public class Lista {
    public Item[] data { get; set; }
}

public class Item {
    public string Codigo { get; set; }
    public string Finalidade { get; set; }
}

Browser other questions tagged

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