locked
Why Does Web API Throw JSON.Parse Error? RRS feed

  • Question

  • User930584213 posted

    I've created the methods below in ASP.NET MVC Web API and every time they are called (checking Developer Tools - Network) they return this error in the Response:

    SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data.

    The response headers tell me that the Content-Type is application/json and the charset is utf-8 and it has Content-Length of 1594 or 311 which appear to be reasonable lengths for these records. I've tried using the default format settings in the Web API and I've tried using the IContentNegotiator interface to return an HttpResponseMessage. Can anyone tell me why Web API is not working out-of-the box in what seems like an uncomplicated situation?

    You can see the XML version in a browser at http://stevegaines.info/api/Certifications/

            public IEnumerable<Certification> GetCertifications()
            {
                IEnumerable<Certification> certifications = null;
                using (var context = new SteveGainesEntities())
                {
                    var query = context.Certifications
                                        .OrderBy(o => o.CertificationDate);
    
                    certifications = query.ToList();
                }
                return certifications;
            }
            [ResponseType(typeof(Certification))]
            public IHttpActionResult GetCertification(int id)
            {
                Certification certification = db.Certifications.Find(id);
                if (certification == null)
                {
                    return NotFound();
                }
    
                return Ok(certification);
            }

    Tuesday, May 17, 2016 1:45 AM

Answers

  • User36583972 posted

    Hi DallasSteve,

    You can try to create a CustomJsonMediaTypeFormatter inherit JsonMediaTypeFormatter. Then Registered in Global.asax.

    The following code in my project for your reference.

    CustomJsonMediaTypeFormatter:

    //using Newtonsoft.Json;
    //using Newtonsoft.Json.Converters;
    //using System.Net;
    //using System.IO;
    //using System;
    //using System.Linq
    //using System.Net.Http;
    //using System.Net.Http.Formatting;
    //using System.Net.Http.Headers;
    //using System.Text;
    //using System.Threading.Tasks;
    
    public class CustomJsonMediaTypeFormatter : JsonMediaTypeFormatter
    
        {
            public JsonSerializerSettings _jsonSerializerSettings;
            public CustomJsonMediaTypeFormatter()
            {
                _jsonSerializerSettings = CustomJsonSettings.Instance;
    
                // Fill out the mediatype and encoding we support
                SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
                SupportedEncodings.Add(new UTF8Encoding(false, true));  //Adjust the parameters according to your own situation
            }
    
            public override bool CanReadType(Type type)
            {
                return true;
            }
    
            public override bool CanWriteType(Type type)
            {
                return true;
            }
    
            public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
            {
                // Create a serializer
                JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings);
    
                // Create task reading the content
                return Task.Factory.StartNew(() =>
                {
                    using (StreamReader streamReader = new StreamReader(stream, SupportedEncodings.First()))
                    {
                        using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader))
                        {
                            return serializer.Deserialize(jsonTextReader, type);
                        }
                    }
                });
            }
    
            public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext)
            {
                // Create a serializer
                JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings);
    
                // Create task writing the serialized content
                return Task.Factory.StartNew(() =>
                {
                    using (StreamWriter streamWriter = new StreamWriter(stream, SupportedEncodings.First()))
                    {
                        using (JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter))
                        {
                            serializer.Serialize(jsonTextWriter, value);
                        }
                    }
                });
            }
        }
    
        public static class CustomJsonSettings
        {
            private static JsonSerializerSettings _settings;
            public static JsonSerializerSettings Instance
            {
                get
                {
                    if (_settings == null)
                    {
                        var settings = new JsonSerializerSettings();
                        settings.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = System.Globalization.DateTimeStyles.AssumeUniversal }); 
                        settings.DateTimeZoneHandling = DateTimeZoneHandling.Local; 
                        settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                        _settings = settings;
                    }
    
                    return _settings;
                }
            }
        }
    

    Global.asax.cs:

     protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(WebApiConfig.Register);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
    
                //add
                GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
                //GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
                //add  CustomJsonMediaTypeFormatterss
                GlobalConfiguration.Configuration.Formatters.Add(new CustomJsonMediaTypeFormatter());
    
    
            }

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 18, 2016 2:23 AM

All replies

  • User36583972 posted

    Hi DallasSteve,

    From your description, I found your Web API work well. I can get the correct XML data from url. So, we are not sure where the error (client or API)

    I suggest you can share us more relevant  error code to help us reproduce the problem.

    Best Regards,

    Yohann Lu

    Tuesday, May 17, 2016 6:00 AM
  • User930584213 posted

    Yohann

    I can also see the XML when I enter the url in a browser.  The problem is when I call the url from AngularJS or jQuery it fails with this error in Developer Tools - Network:

    SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data.

    That's all the error information that I see.

    Tuesday, May 17, 2016 1:40 PM
  • User36583972 posted

    Hi DallasSteve,

    You can try to create a CustomJsonMediaTypeFormatter inherit JsonMediaTypeFormatter. Then Registered in Global.asax.

    The following code in my project for your reference.

    CustomJsonMediaTypeFormatter:

    //using Newtonsoft.Json;
    //using Newtonsoft.Json.Converters;
    //using System.Net;
    //using System.IO;
    //using System;
    //using System.Linq
    //using System.Net.Http;
    //using System.Net.Http.Formatting;
    //using System.Net.Http.Headers;
    //using System.Text;
    //using System.Threading.Tasks;
    
    public class CustomJsonMediaTypeFormatter : JsonMediaTypeFormatter
    
        {
            public JsonSerializerSettings _jsonSerializerSettings;
            public CustomJsonMediaTypeFormatter()
            {
                _jsonSerializerSettings = CustomJsonSettings.Instance;
    
                // Fill out the mediatype and encoding we support
                SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
                SupportedEncodings.Add(new UTF8Encoding(false, true));  //Adjust the parameters according to your own situation
            }
    
            public override bool CanReadType(Type type)
            {
                return true;
            }
    
            public override bool CanWriteType(Type type)
            {
                return true;
            }
    
            public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
            {
                // Create a serializer
                JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings);
    
                // Create task reading the content
                return Task.Factory.StartNew(() =>
                {
                    using (StreamReader streamReader = new StreamReader(stream, SupportedEncodings.First()))
                    {
                        using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader))
                        {
                            return serializer.Deserialize(jsonTextReader, type);
                        }
                    }
                });
            }
    
            public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext)
            {
                // Create a serializer
                JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings);
    
                // Create task writing the serialized content
                return Task.Factory.StartNew(() =>
                {
                    using (StreamWriter streamWriter = new StreamWriter(stream, SupportedEncodings.First()))
                    {
                        using (JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter))
                        {
                            serializer.Serialize(jsonTextWriter, value);
                        }
                    }
                });
            }
        }
    
        public static class CustomJsonSettings
        {
            private static JsonSerializerSettings _settings;
            public static JsonSerializerSettings Instance
            {
                get
                {
                    if (_settings == null)
                    {
                        var settings = new JsonSerializerSettings();
                        settings.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = System.Globalization.DateTimeStyles.AssumeUniversal }); 
                        settings.DateTimeZoneHandling = DateTimeZoneHandling.Local; 
                        settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                        _settings = settings;
                    }
    
                    return _settings;
                }
            }
        }
    

    Global.asax.cs:

     protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(WebApiConfig.Register);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
    
                //add
                GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
                //GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
                //add  CustomJsonMediaTypeFormatterss
                GlobalConfiguration.Configuration.Formatters.Add(new CustomJsonMediaTypeFormatter());
    
    
            }

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 18, 2016 2:23 AM