Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix this error: type org.json.JSONArray cannot be converted to JSONObject

I want remove key and value for ProductCharacteristic ->name. How it can be done in Java and how to fix this error?
type org.json.JSONArray cannot be converted to JSONObject

This is my JSON file:

[
  {
    "id": "0028167072_CO_FIX_INTTV_1008_P3909_IDX0",
    "status": "Active",
    "startDate": "2023-02-12T22:00:00Z",
    "place": [
      {
        "id": "8",
        "apartment": "578",
        "role": "QA",
        "@referredType": "street"
      }
    ],
    "ProductCharacteristic": [
      {
        "id": "CH_100473",
        "valueId": "CH12_1000374_VALUE04141",
        "value": "LTS",
        "name": "Computer"
      }
    ]
  }
]

I tried this code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public static void main(String[] args) {
  // Replace with your actual JSON string of load JSON from file
  String jsonString = "json above";
  JSONObject jsonObject = new JSONObject(jsonString);
  JSONArray productCharacteristics = jsonObject.getJSONArray("ProductCharacteristic");
  // Iterate through each "ProductCharacteristic" object and remove the "name"
  // key-value pair
  for (int i = 0; i < productCharacteristics.length(); i++) {
    JSONObject productCharacteristic = productCharacteristics.getJSONObject(i);
    productCharacteristic.remove("name");
  }
  String updatedJsonString = jsonObject.toString();
  System.out.println("Modified JSON:\n" + updatedJsonString);
}

But this code is not working,I have error message:org.json.JSONArray cannot be converted to JSONObject

>Solution :

Your json is an array, not object – [...] denotes an array, {...} denotes an object. Json specification:

An array is an ordered collection of values. An array begins with [left bracket and ends with ]right bracket.

You need to parse to an array and work with it:

JSONArray jsonArray = new JSONArray(jsonString);
//get first, since the array contains only 1 element
JSONArray productCharacteristics = jsonArray.getJSONObject(0).getJSONArray("ProductCharacteristic");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading