Generating a JSON array in PHP and decoding it in an Android app has encountered an error: org.json.JSONException is throwing an exception stating

I have been using the following PHP code to generate a JSON array:

$jsonData      = array();
$jsonTempData  = array();
$count=0;
$result = $link->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $jsonTempData['id']=$row['_id'];
        $jsonTempData['title']=$row['title'];

        $jsonData[$count++]=json_encode($jsonTempData);

    }
} 
$link->close();
$outputArr = array();

$outputArr['Android']=$jsonData;

print_r( json_encode($outputArr));

and then trying to decode it in my Android application using this code:

 jsonResponse = new JSONObject(Content);
JSONArray array = jsonResponse.optJSONArray("Android");

for(int i=0;i<array.length();i++){
    nm.set_id(array.getJSONObject(i).getInt(DBHelper.ID));

    nm.setTitle(array.getJSONObject(i).getString(DBHelper.TITLE));
}

However, I am encountering an exception in Android:

: org.json.JSONException: No value for id

Could you please help me identify the issue and suggest a solution?

My ultimate objective is to create a 2D array in PHP and convert it into an Array of JSON Objects that can be extracted in an Android app.

Answer №1

The issue arose from a JSON Parsing Exception specifically related to parsing an array

Error: JSONException - The value of type java.lang.String cannot be converted to JSONObject

Solution:

Instead of directly converting the array into a JSON object, I first converted each array item into a string before converting it into a JSON object.

Below is the modified code for your reference:

 jsonResponse = new JSONObject(Content);

 JSONArray array = jsonResponse.optJSONArray("Android");

for(int i=0;i<array.length();i++){

    String strJSON=array.getString(i);

    JSONObject jsonObj = new JSONObject(strJSON);   

    nm.set_id(jsonObj.getInt(DBHelper.ID));

    nm.setTitle(jsonObj.getString(DBHelper.TITLE));
}

Please find below a sample snippet that was tested:

PHP section(test.php)

 <?php
header('Content-type=application/json; charset=utf-8');
$jsonData      = array();
$jsonTempData  = array();

$jsonTempData['id']="id1";
$jsonTempData['title']="title1";

$jsonData[0]=json_encode($jsonTempData);

$jsonTempData['id']="id2";
$jsonTempData['title']="title2";

$jsonData[1]=json_encode($jsonTempData);

$outputArr = array();

$outputArr['Android']=$jsonData;

print_r(json_encode($outputArr));

?>

Resulting JSON:

["{\"id\":\"id1\",\"title\":\"title1\"}","{\"id\":\"id2\",\"title\":\"title2\"}"]

Android portion:

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpGet req = new HttpGet("http://localhost/test.php");

HttpResponse response;
try {
     response = httpClient.execute(req);
    if (response.getStatusLine().getStatusCode() == 200) {

                                        String result;
                                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 8);
                                        StringBuilder sb = new StringBuilder();

                                        String line = null;
                                        while ((line = bufferedReader.readLine()) != null) {
                                        sb.append(line + "\n");
                                        }
                                        result = sb.toString();
                                        Log.d("result:",result.toString());

                                        JSONObject jsonResponse = new JSONObject(result);
                                         JSONArray array = jsonResponse.optJSONArray("Android");

                                         for(int i=0;i<array.length();i++){
                                             String strJSONobj=array.getString(i);
                                             JSONObject json = new JSONObject(strJSONobj);                                           
                                             Log.d("result",json.getString("id"));
                                             Log.d("result",json.getString("title"));                                       
                                         }


                                        }
                                } catch (ClientProtocolException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                } // ClientProtocolException

This solution should resolve the issue. Let us know if you require further assistance.

Answer №2

It appears that the issue lies in encoding individual rows instead of the output array itself. Additionally, it seems like the counter may not be necessary.

Consider the following approach:

$jsonData      = array();
$jsonTempData  = array();
$result = $link->query($sql);

if ($result->num_rows > 0) {
    // obtain data for each row
    while($row = $result->fetch_assoc()) {
        $jsonTempData['id']=$row['_id'];
        $jsonTempData['title']=$row['title'];

        $jsonData[]=$jsonTempData;

    }
} 
$link->close();
$outputArr = array();

$outputArr['Android']=json_encode($jsonData);

print_r($outputArr);

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

Creating a custom class to encapsulate WP_User and easily access its properties and methods

Facing a challenge while developing a WordPress theme, I encountered an issue that seems unsolvable. The task at hand is to "extend" the WP_User class objects with new methods and properties. Initially, my approach was to inherit the class; however, this m ...

What is the method of passing raw JavaScript code to functions in the Yii framework?

When creating a checkbox using the CHtml method, I need to execute specific JavaScript code before and after an AJAX request. Here's the code snippet: echo CHtml::checkBox('markComplete', FALSE, array( 'class' => & ...

Clustering JSON documents with the power of Machine Learning

Looking to conduct document clustering using JSON String data containing various key-value pairs of String and Number types. The goal is to cluster documents based on similar types of keys and values. For example, consider the following JSON Document: {" ...

What is the best way to compress JSON responses?

During a recent interview, I encountered a question that asked how to minify a JSON response. Here is the sample JSON response: { "name": "sample name", "product": "sample product", "address": "sample address" } I am unsure of how to minify this J ...

Tips on performing a null verification within an end-of-day function in PHP

Not too familiar with PHP, but I'm interested in accomplishing something like this $html = $html . <<<EOD <h10>Quick ID:</h10> if (!empty($row->quickid)) I only want to add that row if it has a value and not null. ...

Error encountered: Invalid date time conversion exception occurred while attempting to convert JSON to an object using REST.Json

An error is encountered when attempting to parse the JSON code into an object. The issue appears to be related to the presence of a decimal in the date and time value, specifically '2019.10.5 14:16:14,1000' which triggers an exception. '20 ...

Adding map markers from a JSON feed to your React Google Map - a step-by-step guide!

I'm currently working on a React project that involves integrating Google Maps: const MarkerComponent = ({text}) => <div>{text}</div>; export default class NavMap extends Component { constructor(props) { super(props); this.s ...

What is the most efficient method for transferring rows from an SQL Database to JavaScript?

Recently, I've been exploring the dynamic features of HTML5 IndexedDB controlled by Javascript and how to sync it with an SQL Server database for offline access. The challenge I'm facing is determining the most efficient method to transfer data ...

Guide to creating an uncomplicated quiz using PHP

My goal is to create a quiz with 15 questions. Every time a user lands on the page, they will see a random selection of 5 questions. Each question will have 4 multiple choice answers, with one being correct. The marks allocated for each question are 20, 15 ...

Issue with Google Charts - Chart is unable to render because data table has not been defined

Using Ajax, I attempted to set an Interval for my Google Chart, but unfortunately, the Chart is not being drawn. Instead, I repeatedly receive the error message: "Data table is not defined." every 5 seconds. If you want to see a screenshot of the error mes ...

In JavaScript, the code is designed to recognize and return one specific file type for a group of files that have similar formats (such as 'mp4' or 'm4v' being recognized as 'MOV')

I am working on a populateTable function where I want to merge different file types read from a JSON file into one display type. Specifically, I am trying to combine mp4 and m4v files into MOV format. However, despite not encountering any errors in my code ...

Conceal the server's internal file structure to prevent it from being displayed in sources

When I visit my website and inspect the elements in Google Chrome, I am able to see a list of all the folders on my site under the sources tab. This reveals their original names and allows for the downloading of the entire website code. I am concerned abo ...

Implement a dialog on top of a current web page, achieve php-ajax query result, and enhance with

My website features 'dynamic' content, where 'static' nav-buttons replace specific div contents upon clicking. While I am able to retrieve my php/ajax results in a dialog box, I am struggling with placing this dialog above my current p ...

Sharing a JSON file with another address using Express.js

Currently embarking on my journey to learn Express. I am looking to send a JSON file to another location for processing after receiving it from a webhook request using a POST URL endpoint. The plan is to pass this JSON file to a CPP program. Below is the ...

How to increment hours, minutes, and seconds to a DateTime object in PHP

I have a specific timestamp and I need to add a certain number of hours, minutes, and seconds to it. Here is the method I attempted: date_default_timezone_set('UTC'); $now = DateTime::createFromFormat('U.u', number_format(microtime(t ...

Utilize Reactjs to efficiently showcase a collection of arrays within an object

I am struggling with a JSON file that has nested dropdown mega menu levels and I can't figure out how to map and render multiple levels of arrays and objects to create a tree-like structure. Here is my current JSON Structure: { "megamenu": [ { ...

Transform a Json string into a datatable complete with headers

I am working with a Json string and my goal is to generate a Datatable using the headers provided in that json string. Additionally, I also need to eliminate any escape characters present in the string. Json String [\r\n {\r\n &bs ...

Guide for dividing XML children into multiple children by using PHP and a specified delimiter

I am facing a challenge with an XML child that contains multiple URLs separated by '|' For example: <ImageURL>https://example.com/example.jpg|https://example.com/example2.jpg</ImageURL> I aim to develop a PHP function that can separ ...

Is it possible to limit PHP variables to only accept specific types of values?

I'm curious if it's possible in PHP to restrict a variable to only accept certain types of values that it is defined for. For example, in C#: public int variable = 20; public string variable2 = "Hello World"; So how would this work in PHP if I ...

In JavaScript, when using the fetch function with JSON, it is possible to skip the

Here's an example of fetching review data from within a 'for loop': fetch('https://api.yotpo.com/products/xx-apikey-xx/{{product.id}}/bottomline') In this case, some products may not have reviews and will return a 404 response. Th ...