Transforming ANSI to UTF-8 in Java

I have a JSON-formatted string with characters like \u0025 that I need to convert into their actual character representations.

Is there a direct method in Java to perform this conversion?

Perhaps something like myString.convertToUTF-8();?

I am utilizing the Graph API and receiving responses in JSON format. I intend to use a JSON parser or JavaScript parser for extracting the values.

When trying to assign the response to a variable using the Google Chrome console, I encountered an error stating

Uncaught SyntaxError: Unexpected identifier(…)
.

In JavaScript, I wanted to use JSON.parse(jsonString), but unfortunately, I couldn't successfully assign a value to jsonString.

To convert these characters in Java, I have attempted the following lines of code which did not alter the string:

String responseFromFB = http.sendRequest(url);

byte[] b = responseFromFB.getBytes();
String str= new String(b, "UTF-8");

Below is the sendRequest() function that I'm currently using:

private String httpReq(String URL, String QueryString) throws Exception 
{

    String url = URL;
    String urlParameters = QueryString;

    URL obj = new URL(url);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    con.setRequestMethod("GET");

    con.setRequestProperty("Accept-Charset", "UTF-8");
    con.setRequestProperty("Content-Type", "application/json; charset=utf-8");

    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
    String inputLine;
    StringBuffer response = new StringBuffer();


    while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
    }
    in.close();

    return response.toString();
}

Answer №1

My only requirement was to create

JSONObject fbResponse = new JSONObject(responseFromFacebook);
String decodedFBResponse = fbResponse.toString();

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

What is the correct way to add parameters to a function expression in JavaScript?

function executeFunction(func) { func(); } var mathOperations = function(x, y) { var multiply = x * y; var add = x + y; var subtract = x - y; console.log("Addition: " + add); console.log("Subtraction: " + subtract); console.log("Multiplicati ...

Rendering children using props within the parent container on every child component

I am currently facing an issue while creating a side menu that is supposed to render children within it. The problem occurs when each child gets wrapped in the entire render output of the side menu, and I am struggling to find a solution for this. Even wi ...

How to share custom data with fb_share feature while displaying box count? (find out more below)

I am trying to implement Facebook sharing with box count on my website. The code I am using is as follows: <div id="fbShare"> <a name="fb_share" type="button_count" expr:share_url="data:post.url" href="http://www.facebook.com/sharer.php">S ...

Selenium and AngularJS patiently wait before carrying out specific actions

I have been using selenium to test an AngularJS application and I am encountering an issue where I am unable to perform any actions on the page until it is fully loaded. Although I have considered using Thread.sleep(), I am aware that this is not the most ...

Tips for creating a Discord bot that can respond to inquiries with varying responses

Lately, I've been working on a Discord bot that selects a random response from an array of replies. My goal is for it to display an error message if the question is unknown or if no arguments are provided after the command. I currently have some code ...

Angularjs drop-down menu changes images with animation

<body ng-controller="myCtrl"> <input type="checkbox" ng-model="loaded"/> <select ng-model="list"> <option ng-repeat="option in data.availableOptions" value="{{option.name}}">{{option.id}}</option> </select> {{list}} &l ...

Easy Steps to Retrieve a Formatting String in Vue.js

Hi, I am currently working with this script: <div class="description text-left" v-for="item in siteObject.line_info"> <small>{{siteObject.line_info}}</small> </div> I am currently seeing this view: [ { "lineid": "BN00003054538", " ...

Transmitting information to a server with PHP and cURL

I am encountering an issue while trying to send the following data to my server via API. Request Body: { "nutrients": { "protein": "beans", "fats": "oil", "carbohdrate": "starch" } } Every time I execute the script, the error message bel ...

What is the best way to show a div after successfully sending a post value using AJAX?

How do I show this specific div after a successful AJAX post? This is what I want to display: <div class="love" id="love_0" style="border-radius: 3px; padding: 8px; border: 1px solid #ccc; right: 13px; background: #fff; top: 13px;"> <a class ...

I am experiencing difficulties with displaying my array of JSX elements in the render function of my ReactJS application. What could be

I am currently working on a trivia application and encountering an issue with inserting an updated array of "Choice" elements for each question. Despite my efforts, whenever I attempt to insert an array of JSX elements, the array appears blank. This is qui ...

Switch between different URL tabs seamlessly in NEXT.JS without needing to refresh the page

I have implemented Material UI tabs in my project and I am updating the tab in the URL. However, I do not want the page to refresh every time I switch the tab. Despite using shallow:true in my code, the issue persists. const tabs = [ { label: &apos ...

What is the best way to ensure that $.getJSON executes before $http in Javascript?

Within my web page controller, I have implemented the following Javascript code: $.getJSON('resources/properties/properties.json', function(data) { $scope.properties = data; }); $http({ method: 'GET', url: $scope.pro ...

Preventing Unauthorized Access: Redirecting to Login Page in Vue.js

Here is the code snippet I'm working with: <script> export default{ props:['idStore'], methods:{ addFavoriteStore(event){ $(function () { $(document).ajaxError(functi ...

How can I cancel a JavaScript timer set from a different function?

Can anyone help me with stopping the timer initiated by setInterval() in JavaScript? I need to be able to stop this timer through another function. Is it possible to kill all timers on the page using jQuery or JS? Below is the function where I started the ...

Can each section of the dictionary be individually converted to JSON and then combined into a single valid JSON file?

Is there a way to convert each key-value pair in a dictionary to JSON and then combine them into a single JSON object? I attempted this approach, but it failed and resulted in unexpected output: def to_json(d): j=[] for k,v in d.items(): try: ...

Guide to putting a new track at the start of a jPlayer playlist

I am currently working on a website that utilizes the jPlayer playlist feature. I am facing an issue, as I need to implement a function that adds a song to the beginning of the playlist, but the existing add function only appends songs to the end of the pl ...

The functionality of JQuery .change() is limited to one occurrence

Here is my JavaScript code snippet: jQuery(document).ready(function(){ const select = $('...'); //select element const input = $('...'); //input element select.change(doSomething()); input.change(doSomething()); f ...

There is no error handling for the errors originating from this location

Having trouble parsing a JSON file in my iOS application: Here is the code snippet causing issues: let jsonData:NSDictionary = try JSONSerialization.jsonObject(with: urlData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers ) as! NSDi ...

Is it possible to utilize local state within a Kafka Processor component?

After exploring the Kafka concurrency model, I am still grappling with the question of whether it is possible to have local state in a Kafka Processor without encountering issues. For my specific use case, I am dealing with a topic of updates that need to ...

What is the best way to separate axios functions and components in Vue3?

In my opinion, it's more efficient to separate the axios commands from the vue components. This is how I structured my directories: src api - products.js components - Products.vue products.js import axios from 'axios'; const li ...