Converting Java String to JSONObject in Android: Troubleshooting JSONP issue

Here is the code snippet I am working with:

String json =  request.excutePost("http://192.168.1.42:3000/login_client",urlParameters);
JSONObject jsonObj = new JSONObject(json);

The error displayed in logCat is as follows:

org.json.JSONException: Value {"login_client":"NEW_PASSWORD","token":"2de374f454699aa6fe895c56bc3a111b33f28b72888aec1f5faa77977e232828"} of type java.lang.String cannot be converted to JSONObject

This is the implementation of the executePost function:

public String excutePost(String targetURL, String urlParameters) {
    HttpURLConnection connection = null;
    try {

        //Create connection
        URL url = new URL(targetURL);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length",
                Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream (
                connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.close();
        //Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        StringBuilder response = new StringBuilder(); 
        String line;

        while((line = rd.readLine()) != null)
        {
            response.append(line);
            response.append('\r');
        }
        rd.close();

        Log.e("RESPONSE",response.toString());
        return response.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if(connection != null) {
            connection.disconnect();
        }
    }
}

Answer №1

It seems like the issue lies in the formatting of your string for conversion. It should ideally resemble something along these lines:

"{\"login_client\":\"NEW_PASSWORD\",\"token\":\"2de374f454699aa6fe895c56bc3a111b33f28b72888aec1f5faa77977e232828\"} "

You can try running the following code snippet:

import org.json.simple.JSONObject

String json =  request.excutePost("http://192.168.1.42:3000/login_client",urlParameters);
JSONObject obj = new JSONParser().parse(json).getAsJsonObject();

If you need more guidance, refer to this thread on Stack Overflow: How to convert String to JSONObject in Java

Answer №2

String responseData = new String(request.excutePost("http://192.168.1.42:3000/login_client",urlParameters));
Log.e("Server Response",""+responseData);

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

Is it possible to share data from one controller in a JS file to another JS file? (using AngularJS)

I need to create a table in JavaScript. In one of my JS files, I have a controller with JSON data containing properties like width, height, color, etc. In another JS file, I am building the actual table structure. Here is an example of my AngularJS file: ...

Converting Python dictionaries or JSON data into PHP arrays

There are several threads discussing how to convert python dictionaries to json, but I have not found any information on saving a python dictionary or a json array to a PHP array. I recently inherited a PHP array file that requires some modifications. With ...

Convert JSON into a class with the 'paste special' feature is not available in Visual Studio 2019, even though all web

One useful feature is the ability to easily extract JSON and generate a class from it. In previous versions of VS, Paste Special was a handy tool, but I can't seem to find it in Visual Studio 2019. After checking out this forum thread, it seems addin ...

displaying the identical image from various perspectives

I have an arrow image that I need to display in different angles - top, left, bottom, right. I was considering what would be the best approach: 1: Changing the image direction via CSS and loading the main image <img src="a.png"> <img src="a.png" ...

What is the best way to extract JSON data from an HTML file and store it into a Python

My goal is to extract structured data from a JSON statement embedded in an HTML page. To achieve this, I extracted the HTML content and obtained the JSON using XPath: json.loads(response.xpath('//*[@id="product"]/script[2]/text()').extract_first ...

assign a JSON key to a variable

Is there a way to use a variable as a JSON key in JavaScript? var chtid = "1234" firebase.database().ref().set ({chtid :"hi"}); In this case, chtid is the variable. I have attempted this method without success: var chtid = "1234" firebase.database().re ...

Find matches between elements based on their names or alt tags and retrieve the associated data

UPDATED FOR BETTER UNDERSTANDING--- I am managing a blog where I want to link images automatically to products in my store. These links will be based on an array generated by Shopify. While I don't have extensive knowledge of jQuery and JSON, I beli ...

Selenium cannot locate element by its id

Recently, I started using selenium web-driver to automate my tasks. My main goal is to use it for logging in and navigating/scraping data. public static void main(String[] args) { java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").s ...

WebDriver encountered an ElementNotInteractableException while attempting to locate an element

On my website, there is a menu that has the following code and I am attempting to automate it using Selenium WebDriver with Java. This is the HTML code for the menu: <a href="JavaScript:void(0); class="bars"> ::before ::after I have trie ...

Display JSON data in Angular view by extracting the desired value

Hey there! I have a GET response data with a field like "DeletionDate": "0001-01-01T00:00:00". What I'm trying to achieve is to remove the time part T00:00:00 and only display half of the value in my views. Is there a way to trim the value and show it ...

Converting XML into an Array Using PHP

I attempted to parse an XML string using PHP. Here is an example of the XML: <?xml version="1.0"?> <root> <Log> <Item> <name>![CDATA[James]]</name> <address>![CDATA[Korea]]< ...

Is there a way to convert JSON to a Java object through mapping?

ObjectMapper mapper=new ObjectMapper(); String response1=client.execute(request1, responseHandler); Map jsonObject=mapper.readValue(response1, Map.class); List<Integer> idsList = new ArrayList<>(); JSONArray jsonArray = jsonObject.getJSON ...

Help! How can I prevent using Thread.sleep() multiple times in a selenium test?

Currently, I am facing an issue while writing some Selenium tests. My code includes Thread.sleep after every function call in a method, making it repetitive and messy. I want to find a more optimal solution to replace these repeating Thread.sleep calls. ...

Tips for overcoming the Chrome Extension Error related to the "script-source 'self'" issue

I've been developing a Chrome extension that uses goo.gl to shorten URLs. Here is the code I'm currently working with: $("#ajaxfiller").text(""); //Retrieve entered URL var longUrl = $("#input2").val(); longUrl = '"' + longUrl + &a ...

How to generate a JSON object in a Bash script by capturing the output of a command

As I delve into a shell script, my primary goal is to dynamically transform the output of a command into a JSON object. The structure of the output seems favorable, formatted as "key":"value". In theory, this should be straightforward, right? However, afte ...

Develop a MySQL function that generates a nested JSON Array data structure

To efficiently create a stored procedure in MySQL that extracts specific fields from the database and constructs a formatted JSON object, follow these steps: Begin by initializing a base JSON object as illustrated below: { "form": "Exams tests", ...

An issue occurred when trying to retrieve JSON data using JAXB, but the data can be easily obtained in XML format

package com.marketplace.acres.dummyapp.test; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.xml.bind.annotation.XmlRootElement; @Path("/fortest") @XmlRootElement public class ...

Android encountered an unknown error while trying to access the URL, resulting in an HTTP failure response with a status

My Ionic app runs perfectly fine on iOS, but when I try to run it on Android, I encounter the following error: Http failure response for (unknown url): 0 Unknown Error https://i.stack.imgur.com/8EFna.png I have CORS enabled on the server side and it wor ...

What are the steps to utilize Xamarin's System.JSON?

I'm currently working on deserializing a JSON string into an object using the System.JSON library within Xamarin. Here's what I have so far: ServerConnection.Receive (bb); data = Encoding.ASCII.GetString (bb); try{ MemoryStream stream = new Me ...

Is the drop down click feature malfunctioning in Selenium Java WebDriver?

Can someone please help me identify what is going wrong in my code? WebElement dropdown = driver.findElement(By.xpath("//*[@id='idCallType_100']")); List<WebElement> Options = dropdown.findElements(By.tagName("option")); ...