Wrong JSON format web api

1

I'm having trouble returning json on 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 request 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 is this problem?

    
asked by anonymous 13.05.2014 / 05:05

1 answer

2

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

Create a class with the properties Code and Purpose, fill the array instantiated 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; }
}
    
15.05.2014 / 16:35