JavaScript encountering issues when parsing a string that was serialized using Gson in Java

This question is unique and differs from this one as it specifically addresses the representation of JSON strings serialized from Java in literal form in JavaScript, with a focus beyond just double quotes.

In my scenario, I am serializing a JSON object in Java using Gson, but encountering difficulties when attempting to parse it in Javascript using JSON.parse. The issue arises when dealing with escaped double quotes in the Java object, which is surprising as Gson should handle proper escaping. Since JSON serialization is language-agnostic, transitioning from Java serialization to JavaScript deserialization should be straightforward.

Below is a snippet of the minimal code:

Java serialization

import java.util.*;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

class LOV {
    List<String> values;

    public LOV(List<String> values) {
        this.values = values;
    }
}

public class FooMain {

    private static final Gson gson = new GsonBuilder().serializeNulls().create();

    @SuppressWarnings("unchecked")
    public static <T> T fromJson(String json, Class<T> classOfT) {
        T target = (T) gson.fromJson(json, (Type) classOfT);
        return target;
    }

    public static void main(String args[]) {
        List<String> values = new ArrayList<>();
        values.add("\"foo\"");
        LOV lov = new LOV(values);
        String s = gson.toJson(lov);
        System.out.printf("Stringified JSON is: [%s]\n", s);
        LOV lov2 = fromJson(s, LOV.class);
    }
}

The above code demonstrates successful serialization and deserialization. Additionally, an equals method was implemented for the LOV class to confirm that the re-internalized object (lov2) matches the original serialized object.

The console output from the code is:

Stringified JSON is: [{"values":["\"foo\""]}]

JavaScript internalization

However, attempting to parse the Java-created string in JavaScript results in an error:

Uncaught SyntaxError: Unexpected token f in JSON at position 13(…)

Solution

To address this issue, I followed the accepted answer and suggestions provided in the comments. Several characters needed to be escaped on the Java side, including:

s.replace("\\", "\\\\")
s.replace("\"", "\\\"")
s.replace("'", "\\'")

On the JavaScript side, additional escaping was necessary:

JSON.parse('the string literal prepared by Java'.replace(/\t/g, "\\t"));

While this approach worked, it became complex and ensuring all cases were covered was challenging. Ultimately, I opted for using StringEscapeUtils.escapeEcmaScript, which simplified the process. By applying escapeEcmaScript to the string, a straightforward

JSON.parse('the string literal prepared by Java')
sufficed for JavaScript parsing.

Answer №1

To properly utilize Javascript's JSON.parse function, ensure you use double backslashes. An example implementation is shown below:

JSON.parse('{"data":["\\"bar\\""]}');

Remember to escape the backslash as well in order for it to work correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Change in ReactJS URLs without causing the entire page to refresh when using BrowserRouter

After conducting extensive research and struggling for a solution for quite some time, it appears that I am facing an issue with my ReactJS project. As a beginner in ReactJS, I have developed a game (a quiz) with multiple levels where the component remains ...

What steps can I take to fix the Error with webpack's style hot loader JavaScript?

Just starting out with native script and encountered an issue when running this code: <template> <view class="container"> <text class="text-color-primary">My Vue Native Apps</text> </view> </template> &l ...

Issues with transmitting query responses via TCP in a Node.js client/server system

I've been working on creating a middleman system to connect my database with various node projects. I know my code is not the best, but I'm under pressure to complete this project for university and meet deadlines. Server-side code: const net = ...

What is the best way to retrieve the post JSON data in the event of a 404 error?

When my service call returns a 404 error, I want to display the server's message indicating the status. The response includes a status code and message in JSON format for success or failure. This is an example of my current service call: this._trans ...

Running a JavaScript test using the Mocha framework with an 'import' statement for a JS file

I am familiar with the module.export and require method: Requiring external js file for mocha testing While it is useful when dealing with modules, I find it inconvenient as I now need to test code in a specific file. For example, I have code in a file: ...

A Guide to Parsing JSON Data in JavaScript

I am facing an issue with the JSON received from an AJAX call. The problem lies in the unexpected '\t' after a bullet point, causing a JavaScript error in the JSON.Parse(data.d) function. Can you provide advice on how to address this situati ...

Default Value for Null in Angular DataTable DTColumnBuilder

What is the best way to define a default value in case of null? $scope.dtOptions = DTOptionsBuilder .fromSource('api/Restt/List'); $scope.dtColumns = [ DTColumnBuilder.newColumn('modi ...

Creating a JSON object hashtable using jsHashtable: A step-by-step guide

I have a good understanding of how to create a hashtable from scratch using jshashtable. For instance: <script type="text/javascript" src="jshashtable.js"></script> <script type="text/javascript"> var typesHash = new Hashtable(); ...

Can I safely keep a JWT in localStorage while using ReactJS?

As I work on developing a single page application with ReactJS, one question comes to mind. I came across information indicating that using localStorage may pose security risks due to XSS vulnerabilities. However, given that React escapes all user input, ...

Struggling with TypeScript errors due to React.HTMLProps for HTMLAnchorElement

When trying to extend a React component with React.HTMLProps without explicitly defining onClick in the attribute list, ESLint complains when passing onClick as an attribute while using the component. Here's an example of the code: The React componen ...

What causes req.sessions to show an empty object instead of the expected value?

I've been grappling with a small issue while learning express.js. I am struggling to save sessions in the browser so that users don't have to log in every time they visit. I am using cookie-session for this purpose. When I send the login data fro ...

The website displays perfectly in Atom, however, it is not functional in any web browser

My website is currently in the development phase, and I'm experiencing issues with certain div elements not positioning correctly once the site goes live. Specifically, the "Follow Us" tab at the bottom of the site, among other divs, has been affecte ...

What steps can I take to expand this on a grander level?

I have a code snippet for a personality quiz, but I'm facing an issue with increasing its size. Here's the HTML code: <h3>1. What is your favorite color?</h3> <input type="radio" name="q1" value="A" /> A. Red. <input type="r ...

Where can the Path be found for Json inside App Phonegap?

Having some trouble with my Phonegap App! Everything seems to be working fine when I test it in my browser. However, once I compile it into an APK and install it on my phone, it's unable to find the JSON data. I'm a beginner in programming and a ...

Integrate Ruby parameter into JavaScript in Rails

I have a div that I want to turn into a link to another page. Typically, we achieve this using link_to link. <% for item in @items %> <%= link_to "Item", item %> # -> or <%= link_to(item) %> <% end %> However, I need the ent ...

Issue with the gulp-babel plugin: Files within the Plugin/Preset should only export functions, not objects

I have started to integrate JavaScript 2015 (ES6) into my Ionic v1 app: package.json { "name": "test", "version": "1.0.0", "dependencies": { "@ionic-native/deeplinks": "^4.18.0", "cordova-android": "7.0.0", "cordova-android-support-gra ...

Forward user to a subdomain once they have successfully logged in on an Angular 2 application

I've been working on an Angular 2 application and I'm looking to redirect users from www.example.com to admin.example.com after they successfully log in. What is the best way to accomplish this using Angular 2? Additionally, how can I test this f ...

What is the best way to choose an Animatedmodal that can showcase various demos while using just one ID?

I am currently customizing my website and utilizing the AnimatedModal.js framework. I have successfully displayed content in one modal, but encountered difficulty when attempting to create multiple modals as they all share the same ID. My question is, how ...

how to use jQuery to hide a flash-containing div without losing its content

Hello, I created a modal with jQuery UI that is displaying in front of a flash movie. However, the HTML content inside the modal appears corrupted. I attempted to hide the movie just before the modal is triggered and make it reappear after closing the mo ...

Choosing from a variety of tr elements

I'm working with a table in HTML that has about 100 rows. I would like to apply different colors to specific groups of rows, such as making rows 1-10 red and rows 20-40 blue. Using nth-child seems like an option, but it can get quite verbose if I nee ...