'How to get the JSON Object from String array?
I have a String array that is extracted from the query. I want to know to iterate over JSON objects using that String array. Query example = "Select Name,ID from Account". So I've extracted Name and ID from the query and stored them in String soqlQuerySplit. Code is as follows-
String response = EntityUtils.toString(httpResponse.getEntity());
String extractStringAfterSelect = StringUtils.substringAfter(updatedSOQLQuery, "select ");
String extractStringBeforeFrom = StringUtils.substringBefore(extractStringAfterSelect, " from");
String[] soqlQuerySplit = extractStringBeforeFrom.split(",");
if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()
&& httpResponse.getEntity().getContentType().getValue().contains(ContentType.APPLICATION_JSON.getMimeType())) {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("records");
List<String> listQueryFields = new ArrayList<>();
for (int totalRecords = 0; totalRecords < jsonArray.length(); totalRecords++) {
JSONObject jsonQueryFields = jsonArray.getJSONObject(totalRecords);
for (int i = 0; i < soqlQuerySplit.length; i++) {
String queryFields =jsonQueryFields.getString(String.valueOf(i));
listQueryFields.add(queryFields);
}
}
updatedListModuleFormFields = listQueryFields.toArray(String[]::new);
In the above code response JSON is like this
{
"totalSize": 4,
"done": true,
"records": [
{
"attributes": {
"type": "Account",
"url": "/services/data/v54.0/sobjects/Account/0015j00000ZqX9fAAF"
},
"Name": "rpatest",
"Id": "0015j00000ZqX9fAAF",
"Phone": "123456790"
},
{
"attributes": {
"type": "Account",
"url": "/services/data/v54.0/sobjects/Account/0015j00000ZqXCPAA3"
},
"Name": "rpatest",
"Id": "0015j00000ZqXCPAA3",
"Phone": "123456790"
},
{
"attributes": {
"type": "Account",
"url": "/services/data/v54.0/sobjects/Account/0015j00000ZqXCUAA3"
},
"Name": "rpatest",
"Id": "0015j00000ZqXCUAA3",
"Phone": "123456790"
},
{
"attributes": {
"type": "Account",
"url": "/services/data/v54.0/sobjects/Account/0015j00000ZqdEeAAJ"
},
"Name": "rpatest",
"Id": "0015j00000ZqdEeAAJ",
"Phone": "123456790"
}
]
}
I'm not sure what to do in the second 'for' loop, I tried using getString method but it is throwing 'JSONObject [0]' not found error.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
