简体   繁体   中英

How can I get JSON result from Asp.Net Web Api 2 that looks like Google API response?

Using ASP.net Web api 2 how can I response in google like manner: https://developers.google.com/maps/documentation/geocoding/intro

My model:

[DataContract]
public class ProductResponse
{
    [DataMember]
    public string Status_Message { get; set; }

    [DataMember]
    public List<Product> Products { get; set; }
}

My Controller:

public ProductResponse GetAllProducts()
    {
        ProductResponse response = new ProductResponse();
        try
        {
            using (SQLServerWrapper sqlConn = new SQLServerWrapper())
            {
                using (SqlCommand command = sqlConn.PrepareCommand(Product.SQLSelect))
                {
                    SqlDataReader reader = command.ExecuteReader();
                    response.Products = reader.Select<Product>(Product.FromDataReader).ToList();
                }
            }
            response.Status = "OK";
        }
        catch (Exception ex)
        {
            response.Status = "ERROR";
        }

        return response;
    }

All that works good. My question how can I switch reponse to JSON type that is readable by browsers?

Simple, just request an answer in json :)

The type of the serialization is determined by an header in your request, or the absence of it.

Content-Type: application/json
Accept: application/json

By default asp.net web api can serialize eiter in xml or json.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM