JSON
error handling
data parsing
programming
debugging

Unexpected character encountered while parsing value

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The error "Unexpected character encountered while parsing value" usually means a parser expected valid JSON input and received something else. In .NET, this message often comes from Json.NET when the input begins with an unexpected character such as <, H, or an unquoted token. The real problem is rarely the parser itself. It is usually that the code is parsing the wrong content or malformed JSON.

Check What the Input Actually Contains

The first debugging step is to inspect the raw payload before deserializing it. Many cases turn out to be one of these:

  • an HTML error page instead of JSON
  • plain text such as Hello instead of a JSON string like "Hello"
  • malformed JSON with single quotes, trailing commas, or missing quotes
  • an empty response body

A simple diagnostic example in C# makes the issue obvious.

csharp
1using Newtonsoft.Json;
2using System;
3
4string payload = "<html>500 Server Error</html>";
5
6try
7{
8    var result = JsonConvert.DeserializeObject<object>(payload);
9    Console.WriteLine(result);
10}
11catch (JsonReaderException ex)
12{
13    Console.WriteLine(ex.Message);
14}

This fails because the parser expects JSON, but the first character is <, which usually indicates HTML.

Validate JSON Shape, Not Just Content Type

Even when an API claims to return JSON, the body still has to be syntactically valid. JSON requires double-quoted property names and string values where appropriate.

Valid JSON:

json
1{
2  "name": "Alice",
3  "age": 30
4}

Invalid JSON:

text
1{
2  name: 'Alice',
3  age: 30,
4}

The second example looks JavaScript-like, but it is not valid JSON. Parsers are strict here for good reason.

Handle HTTP Responses Before Deserializing

A frequent mistake is calling JSON deserialization on every HTTP response body without checking the status code or content type first.

csharp
1using System;
2using System.Net.Http;
3using System.Threading.Tasks;
4using Newtonsoft.Json;
5
6public static async Task Main()
7{
8    using var client = new HttpClient();
9    var response = await client.GetAsync("https://example.com/api/products/1");
10    var payload = await response.Content.ReadAsStringAsync();
11
12    if (!response.IsSuccessStatusCode)
13    {
14        Console.WriteLine(payload);
15        return;
16    }
17
18    var product = JsonConvert.DeserializeObject<Product>(payload);
19    Console.WriteLine(product.Name);
20}
21
22public class Product
23{
24    public string Name { get; set; }
25}

This pattern protects you from trying to deserialize an HTML error page or other non-JSON response.

Match the Target Type to the JSON Structure

Sometimes the input is valid JSON, but the code expects the wrong shape. For example, deserializing a JSON array into an object type produces confusing errors downstream.

If the payload is:

json
1[
2  { "name": "Alice" },
3  { "name": "Bob" }
4]

then the target type must be something like List<Person>, not Person.

Likewise, a bare JSON string such as "ok" is valid JSON, but it cannot be deserialized into a complex object without additional handling.

Log Raw Payloads Safely

When this error happens in production, logging the first part of the raw response is often enough to reveal the issue. Do that carefully if the payload may contain secrets or personal data. A truncated sanitized sample is usually sufficient.

The parser's character position in the exception message is also useful. If it fails at the first character, the payload is often not JSON at all.

Common Pitfalls

  • Attempting to parse HTML, plain text, or an empty body as JSON.
  • Assuming an API always returns JSON even for error responses.
  • Sending JavaScript-style object literals with single quotes or trailing commas to a strict JSON parser.
  • Deserializing valid JSON into the wrong target type.
  • Ignoring the raw payload and debugging only from the exception message.

Summary

  • This error usually means the parser expected JSON and received invalid or non-JSON input.
  • Inspect the raw payload first, especially the first few characters.
  • Check HTTP status codes and response content before calling a JSON deserializer.
  • Make sure the JSON syntax is valid and the target type matches the payload shape.
  • Logging a safe sample of the raw response is often the fastest way to find the real cause.

Course illustration
Course illustration

All Rights Reserved.