How to deserialize JSON with escaped double quotes?

1.4K    Asked by AnishaDalal in Salesforce , Asked on Apr 23, 2021

JSON(I am working with): JSONLinter confirms this is a valid JSON.

{ "errors": [ { "params": { "password": "size must be between 4 and 30", "loginId": "must match "^[a-zA-Z0-9_]*$"" } } ] }
Attempt 1(Using JSONParser:
String str = '{ "errors": [ { "params": { "password": "size must be between 4 and 30", "loginId": "must match "^[a-zA-Z0-9_]*$"" } } ] }'; JSONParser parser = JSON.createParser(str); while(parser.nextToken() != null){ parser.nextToken(); }
Fails:
▸ ERROR: System.JSONException: Unexpected character ('^' (code 94)): was ▸ expecting comma to separate OBJECT entries at input location [1,99] ▸ ERROR: Class.System.JSONParser.nextToken: line 94, column 1 ▸ AnonymousBlock: line 3, column 1 ▸
AnonymousBlock: line 3, column 1
Attempt 2(JSON2Apex option):
public class JSON2Apex { public class Errors { public Params params; } public List errors; public class Params { public String password; public String loginId; } } String str = '{ "errors": [ { "params": { "password": "size must be between 4 and 30", "loginId": "must match "^[a-zA-Z0-9_]*$"" } } ] }'; JSON2Apex obj = (JSON2Apex)JSON.deserialize(str, JSON2Apex.class);
Fails:
▸ ERROR: System.JSONException: Unexpected character ('^' (code 94)): was ▸ expecting comma to separate OBJECT entries at [line:1, column:99] ▸ ERROR: Class.System.JSON.deserialize: line 15, column 1 ▸ AnonymousBlock: line 2, column 1 ▸ AnonymousBlock: line 2, column 1
Attempt 3(deserializeUntyped):
String str = '{ "errors": [ { "params": { "password": "size must be between 4 and 30", "loginId": "must match "^[a-zA-Z0-9_]*$"" } } ] }'; Map jsonObj = (Map)JSON.deserializeUntyped(str);
Fails:
▸ ERROR: System.JSONException: Unexpected character ('^' (code 94)): was ▸ expecting comma to separate OBJECT entries at [line:1, column:99] ▸ ERROR: Class.System.JSON.deserializeUntyped: line 11, column 1 ▸ AnonymousBlock: line 2, column 1 ▸ AnonymousBlock: line 2, column 1
Attempt 4(replace the problem causing double quote in JSON):
String str = '{ "errors": [ { "params": { "password": "size must be between 4 and 30", "loginId": "must match "^[a-zA-Z0-9_]*$"" } } ] }'; Map jsonObj = (Map)JSON.deserializeUntyped(str.replaceAll('"', '\"'));

Still fails:

▸ ERROR: System.JSONException: Unexpected character ('^' (code 94)): was ▸ expecting comma to separate OBJECT entries at [line:1, column:99] ▸ ERROR: Class.System.JSON.deserializeUntyped: line 11, column 1 ▸ AnonymousBlock: line 2, column 1 ▸ AnonymousBlock: line 2, column 1

Answered by Angela Baker

This is valid JSON.

{ "errors": [ { "params": { "password": "size must be between 4 and 30", "loginId": "must match "^[a-zA-Z0-9_]*$"" } } ] }
This is not:
String str = '{ "errors": [ { "params": { "password": "size must be between 4 and 30", "loginId": "must match "^[a-zA-Z0-9_]*$"" } } ] }';
Why? Because in Apex, backslash is an json escape character in a string literal. If you want that backslash to carry through to the in-memory representation of the string (your JSON), you must escape it in your source code:
String str = '{ "errors": [ { "params": { "password": "size must be between 4 and 30", "loginId": "must match \"^[a-zA-Z0-9_]*$\"" } } ] }';
Otherwise, Apex removes it, yielding an in-memory string that is not valid JSON because nested quote marks are not escaped:
"loginId": "must match "^[a-zA-Z0-9_]*$""

You don't need to use replaceAll() or anything fancy to fix this (and in fact, you can't - by the time you could call replaceAll(), the string's already broken and has no backslashes in it). Your logic is correct but. It's just in how you're writing string literals in your source code and that’s the reason you are struggling to deserialize JSON escape.



Your Answer

Answer (1)

Deserializing JSON with escaped double quotes can be straightforward depending on the programming language you are using. Below are examples in a few popular languages:

In Python, you can use the json module to deserialize JSON strings. If your JSON string contains escaped double quotes, you need to ensure that the string is correctly formatted as a valid JSON string.

Here's an example:

import json# JSON string with escaped double quotesjson_str = "{"name": "John", "age": 30, "city": "New York"}"# Deserialize the JSON stringdata = json.loads(json_str)# Accessing dataprint(data)print(data['name'])print(data['age'])print(data['city'])JavaScript

In JavaScript, you can use the JSON.parse method to parse a JSON string. Similarly, ensure your JSON string is correctly formatted:

  // JSON string with escaped double quotesvar jsonStr = "{"name": "John", "age": 30, "city": "New York"}";// Deserialize the JSON stringvar data = JSON.parse(jsonStr);// Accessing dataconsole.log(data);console.log(data.name);console.log(data.age);console.log(data.city);

In Java, you can use the Jackson library to deserialize JSON strings. Here’s an example:

import com.fasterxml.jackson.databind.ObjectMapper;

  public class JsonDeserializeExample {    public static void main(String[] args) {        String jsonStr = "{"name": "John", "age": 30, "city": "New York"}";                ObjectMapper objectMapper = new ObjectMapper();                try {            Person person = objectMapper.readValue(jsonStr, Person.class);            System.out.println(person);        } catch (Exception e) {            e.printStackTrace();        }    }}class Person {    private String name;    private int age;    private String city;    // Getters and setters    @Override    public String toString() {        return "Person [name=" + name + ", age=" + age + ", city=" + city + "]";    }}C#In C#, you can use the JsonConvert class from the Newtonsoft.Json library:using Newtonsoft.Json;using System;public class Program{    public static void Main()    {        string jsonStr = "{"name": "John", "age": 30, "city": "New York"}";                Person person = JsonConvert.DeserializeObject(jsonStr);                Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, City: {person.City}");    }}

public class Person

  {    public string Name { get; set; }    public int Age { get; set; }    public string City { get; set; }}

Notes

Ensure that your JSON string is correctly formatted and that the double quotes are properly escaped.

Handle exceptions where necessary to manage any errors that occur during deserialization.

These examples should help you deserialize JSON strings with escaped double quotes in various programming languages.

5 Months

Interviews

Parent Categories