3

I am developing a ASP.NET MVC Web Api. Project. I am returning data with JSON format. Before I return data to user I serialize data using JsonConvert.SerializeObject to change their json property names.My code return data in JSON format. But with an issue. That is it always return data into string even if the data is array or object.

This is my action method that returns json.

public HttpResponseMessage Get()
        {
            IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
            List<ContentRegion> regions = new List<ContentRegion>();
            if(dbRegions!=null && dbRegions.Count()>0)
            {
                foreach(var region in dbRegions)
                {
                    ContentRegion contentRegion = new ContentRegion
                    {
                        Id = region.Id,
                        ImageUrl = Url.AbsoluteContent(region.ImagePath),
                        SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.SmallThumbSuffix)),
                        MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.MediumThumbSuffix)),
                        Name = region.Name,
                        MmName = region.MmName,
                        Description = region.Description,
                        MmDescription = region.MmDescription,
                        Latitude = region.Latitude,
                        Longitude = region.Longitude
                    };
                    regions.Add(contentRegion);
                }
            }
            string json = JsonConvert.SerializeObject(regions);
            if(!string.IsNullOrEmpty(json))
            {
                json = json.Trim(new char[] { '"' });
            }
            return new HttpResponseMessage(HttpStatusCode.OK)
            {

                Content = new ObjectContent(json.GetType(),json,Configuration.Formatters.JsonFormatter)
            };
        }

Actually this code should return Json array. But when I parse data from client (from Android using Volley). It cannot be parsed into Json Array.

This is the data I get:

enter image description here

As you can see the double quote both in the beginning and at the end. The reason I cannot parse it into array in Volley is it is returning as a string because of that double. How can I serialize it trimming that quote? I used trim, but not removed.

1
  • Take a look here. It might help you even if you use MVC. Commented Jun 2, 2016 at 13:15

4 Answers 4

1

You are unnecessarily complicating things. In Web API you can return JSON just by returning any object inside the built-in methods, the framework will serialize it for you.

public IHttpActionResult Get()
{
    IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
    List<ContentRegion> regions = new List<ContentRegion>();
    if(dbRegions != null && dbRegions.Count() > 0) {
        foreach(var region in dbRegions)
        {
            ContentRegion contentRegion = new ContentRegion
            {
                Id = region.Id,
                ImageUrl = Url.AbsoluteContent(region.ImagePath),
                SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.SmallThumbSuffix)),
                MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.MediumThumbSuffix)),
                Name = region.Name,
                MmName = region.MmName,
                Description = region.Description,
                MmDescription = region.MmDescription,
                Latitude = region.Latitude,
                Longitude = region.Longitude
            };
            regions.Add(contentRegion);
        }
    }

    return Ok(regions);
}

As an aside: from what I can see you are mapping manually your domain objects into DTOs: take into consideration the use of an automatic mapping mechanism like AutoMapper.

Sign up to request clarification or add additional context in comments.

8 Comments

It is not working because return json properties become something like this
{"<Id>k__BackingField":1,"<ImageUrl>k__BackingField":
It was not properly serialized.
Of course you have to set the right Accept: application/json header from the client, or else the framework will not know which Content-Type your client expects
But I have media type formatter mapping by query string. I set format by query string and it is not working as well.
|
1

I am not sure this is the best solution or not. I solved the problem using this way.

This is my action method

public HttpResponseMessage Get()
        {
            try
            {
                IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
                List<ContentRegion> regions = new List<ContentRegion>();
                if (dbRegions != null && dbRegions.Count() > 0)
                {
                    foreach (var region in dbRegions)
                    {
                        ContentRegion contentRegion = new ContentRegion
                        {
                            Id = region.Id,
                            ImageUrl = Url.AbsoluteContent(region.ImagePath),
                            SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.SmallThumbSuffix)),
                            MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.MediumThumbSuffix)),
                            Name = region.Name,
                            MmName = region.MmName,
                            Description = region.Description,
                            MmDescription = region.MmDescription,
                            Latitude = region.Latitude,
                            Longitude = region.Longitude
                        };
                        regions.Add(contentRegion);
                    }
                }
                string json = JsonConvert.SerializeObject(regions);

                return new HttpResponseMessage(HttpStatusCode.OK)
                {

                    Content = new StringContent(json, Encoding.Default, "application/json")
                };
            }
            catch
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError);
            }
        }

Comments

0

It's not required to convert object to json string. You can try :

return Request.CreateResponse<List<ContentRegion>>(HttpStatusCode.OK,regions);

Not tested.

Comments

0
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); 


Use this line in your WebApiConfig.



And here your code should be


  public HttpResponseMessage Get()
        {
            IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
            List<ContentRegion> regions = new List<ContentRegion>();
            HttpResponseMessage temp = ControllerContext.Request.CreateResponse(HttpStatusCode.OK, "");
            if (dbRegions != null && dbRegions.Count() > 0)
            {
                foreach (var region in dbRegions)
                {

                    ContentRegion contentRegion = new ContentRegion
                    {
                        Id = region.Id,
                        ImageUrl = Url.AbsoluteContent(region.ImagePath),
                        SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.SmallThumbSuffix)),
                        MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.MediumThumbSuffix)),
                        Name = region.Name,
                        MmName = region.MmName,
                        Description = region.Description,
                        MmDescription = region.MmDescription,
                        Latitude = region.Latitude,
                        Longitude = region.Longitude
                    };
                    regions.Add(contentRegion);
                }
            }

            temp = ControllerContext.Request.CreateResponse(HttpStatusCode.OK, regions);
            return temp;

            //string json = JsonConvert.SerializeObject(regions);
            //if (!string.IsNullOrEmpty(json))
            //{
            //    json = json.Trim(new char[] { '"' });
            //}
            //return new HttpResponseMessage(HttpStatusCode.OK)
            //{

            //    Content = new ObjectContent(json.GetType(), json, Configuration.Formatters.JsonFormatter)
            //};
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.