2

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372
  • Take a look [here](http://stackoverflow.com/questions/34851481/how-to-change-file-to-retrieve-data-from-json/34898867#34898867). It might help you even if you use MVC. – magn Jun 02 '16 at 13:15

4 Answers4

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.

Federico Dipuma
  • 17,655
  • 4
  • 39
  • 56
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);
            }
        }
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372
0

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

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

Not tested.

Anupam Singh
  • 1,158
  • 13
  • 25
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)
            //};
        }
pBanyal
  • 21
  • 7