What is the issue with the character set?

Attempting to send request data from JavaScript to Java using JSON format. In JavaScript, the request body appears as:

{
    "id": "3",
    "name": "Chicken pasta",
    "description": "Lets make chicken pasta",
    "category": "Unassigned",
    "favorite": true,
    "prepTime": "",
    "cookTime": "",
    "ingredients": [
        {}
    ],
    "steps": [],
    "user": {
        "id": "2",
        "username": "user2"
    }
}

However, on the server side (in my Java controller), it is represented as:

%7B%0A%09%22id%22%3A+%223%22%2C%0A%09%22name%22%3A+%22Chicken+pasta%22%2C%0A%09%22description%22%3A+%22Lets+make+chicken+pasta%22%2C%0A%09%22category%22%3A+%22Unassigned%22%2C%0A%09%22favorite%22%3A+true%2C%0A%09%22prepTime%22%3A+%22%22%2C%0A%09%22cookTime%22%3A+%22%22%2C%0A%09%22ingredients%22%3A+%5B%0A%09%09%7B%7D%0A%09%5D%2C%0A%09%22steps%22%3A+%5B%5D%2C%0A%09%22user%22%3A+%7B%0A%09%09%22id%22%3A+%222%22%2C%0A%09%09%22username%22%3A+%22user2%22%0A%09%7D%0A%7D=

This results in a JSON parsing exception. How can I resolve this encoding issue?

Answer №1

Make sure to decode the URL string received from the server before attempting to parse it as JSON. Refer to this Stack Overflow thread for guidance on decoding URLs in Java.

Answer №2

Ah, Thomas, you were absolutely correct and I managed to figure it out on my own as well. Instead of using URLDecoder.decode, I decided to write a few lines of code by myself :)

   public static String toDecimal (String hexStr) {
        char[] hex = hexStr.toCharArray();
        char current;
        String result = "";
        for (int i=0;i<hex.length;i++) {
            if (hex[i] == '%') {
                current = (char) ((toDecimal(hex[i+1]) * 16) + toDecimal(hex[i+2]));
                i+=2;
            } else {
                if (hex[i] == '+') {
                    current = ' ';
                } else {
                    current = hex[i];
                }
            }
            result += current;
        }
        while (!(result.endsWith("}") || result.endsWith("]"))) {
            result = result.substring(0, result.length()-1);
        }
        return result;
    }

    private static int toDecimal (char hex) {
        switch (hex) {
            case '0': return 0;
            case '1': return 1;
            case '2': return 2;
            case '3': return 3;
            case '4': return 4;
            case '5': return 5;
            case '6': return 6;
            case '7': return 7;
            case '8': return 8;
            case '9': return 9;
            case 'A': return 10;
            case 'B': return 11;
            case 'C': return 12;
            case 'D': return 13;
            case 'E': return 14;
            case 'F': return 15;
        }
        return -1;
    }

The functionality of my custom function is identical to the previously mentioned URLDecoder.decode method. However, my function also removes all characters from the end until either '}' or ']' is encountered. Interestingly, when extracting a string from JavaScript, I notice that it ends with an '=' symbol, which puzzles me.

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

Node.js is throwing GitHub API 401 Bad Credentials error, whereas curl is not encountering the

I am attempting to authenticate on Enterprise GitHub using @octokit/rest. When I execute the following Curl command, I receive a list of API URLs: curl -u "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80edf9c0e5ede1e9ecaee3e ...

Issues have been raised with IE11's refusal to accept string(variable) as a parameter for the localStorage

Why is it that Internet Explorer does not recognize a string variable as a parameter for the setItem method, even though it works fine in Chrome? For example, in IE: This code snippet works: var itemName = 'anyname'; localStorage.setItem(itemN ...

When saving a canvas as an image, it only results in a blank, transparent image

I have a situation where I am iterating through an array of image elements sourced from a local folder, attaching them to a canvas. However, when attempting to save the canvas as an image, it is not being saved correctly. The resulting image appears to mat ...

What is the best method to assign values to AngularJS controller variables using Python Selenium or the JavaScript console?

After utilizing Python Selenium and AngularJS for a few months, I am currently attempting to adjust certain AngJS variables (specifically the aslider filter from here) and refresh the page in order to extract some data. Below is the code I am using for thi ...

Transforming a complex JSON object into a pandas DataFrame

My current task involves working with a JSON file containing nested fields (arrays) that I want to convert into a Pandas dataframe. { "_id": "2026", "dataDate": 1537920000000, "dataYear": 2018, " ...

Displaying information from an array using AngularJS

I'm struggling to display data from an array and I could use some help. Here's a snippet from my service.js file: this.fetchData = function() { var myArray = $resource('url', {method: 'get', isArray: true}); myArray ...

What is the process for creating a widget that can be seamlessly integrated into someone’s website and hosted on your own site

In relation to this previous question. After researching JSONP and conducting some tests, I've realized that I am completely clueless about what I'm doing... What is required? I am developing a customer service tool for people to integrate in ...

What is the best way to align an avatar within a cardHeader component in the center?

Recently, I've been working on a frontend project using Material UI. In my design, I have cards that display data, and I wanted to include an avatar in the center of each card. Despite using a card header to insert the avatar, I struggled to align it ...

Learn how to fetch user-selected options in Node.js and display the corresponding file contents in a textarea after submission

Hello, I am new to Node.js so please be patient with me. I am struggling to figure out how to retrieve the selected option from a drop-down list after a user submits it and then perform an action based on that choice. Here is an example of what I have in m ...

Decoding JSON in Angular

Hey there, I'm facing a bit of a challenge. My Angular JSON GET process is grabbing the results properly, but I'm struggling to parse and access individual values from the result. Here's the string result that I receive: {"result":[{"sys_i ...

What is the most effective way to add images to a table using JavaScript?

Is there a way to insert images into the "choicesDiv" without having to make changes to the HTML & CSS? Here is the table code: <table id="choices"> <tr> <td><div class="choicesDiv" value="1"></div></td> ...

The new and improved Vue 3 computed feature in the Composition API

The temporary object appears as: tmp : { k1: { k2 : { k3 : [abc, def] } } To access k3 in the setup, it should be: tmp.value.k1.k2.k3[0 or 1]. I am looking to change its name to something like - k3_arr = tmp.value.k1.k2.k3; Within my Vue single componen ...

Navigating to a new page by selecting a row in a material-ui table

Within my project, there is a file labeled route-names.js containing the following entry: export const REVIEW_FORM_URL = '/custom-forms/:customFormId'; In one of my material-ui tables with multiple rows, clicking on a row reveals the id as ...

A guide to implementing drag and drop functionality using JavaScript

I have developed a unique drag and drop application that features both a left and right panel. The issue I am facing is that when I drag the ball from the left panel to the right panel, it does get dragged successfully. However, the problem arises when the ...

How can I pass a string value from C++ to JavaScript in a Windows environment using Visual Studio 2008?

In my current project, I have successfully implemented an IDL for passing a string value from JavaScript to C++. The JavaScript code effectively passes a string value to the C++/COM object. [id(1), helpstring("method DoSomething")] HRESULT DoSomething([in ...

What are the steps to setting up SystemJS with Auth0?

I am having trouble configuring SystemJS for Auth0 (angular2-jwt) and Angular 2.0.0-beta.6 as I keep encountering the following error message: GET http://localhost:3000/angular2/http 404 (Not Found)fetchTextFromURL @ system.src.js:1068(anonymous function) ...

Function that returns an Observable<Boolean> value is null following a catch block

Why is the login status null instead of false in this method? // In the method below, I am trying to return only true or false. isLoggedIn(): Observable<boolean> { return this .loadToken() .catch(e => { this.logger ...

Display only one field and hide the other field using a jQuery IF/ELSE statement

Hey there! I have a situation where I need to toggle between two fields - one is a text field and the other is a text_area field. When a user clicks on one field, the other should be hidden and vice versa. I've tried using JQuery for this: $(document ...

Understanding JavaScript for Reading a Website's "Local Storage"

Can the local storage of one website be accessed by a different domain, or is it restricted to only the domain that saved it? ...

What is the process for searching a specific column in a Vuetify v-data-table that is not included in the headers?

Header for Product Data: headers: [ { text: "Product Name", value: "name" }, { text: "Quantity", value: "quantity" }, { text: "Price", value: "price" }, { text: "Orders", value: &quo ...