Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json data serialized with JsonConvert.SerializeObject is always string in ASP.NET Web API

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.

like image 457
Wai Yan Hein Avatar asked May 11 '26 06:05

Wai Yan Hein


2 Answers

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.

like image 129
Federico Dipuma Avatar answered May 12 '26 22:05

Federico Dipuma


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);
            }
        }
like image 22
Wai Yan Hein Avatar answered May 12 '26 22:05

Wai Yan Hein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!