0

I'm currently working on the below JSON. Sometimes records in matches return null, instead of record. And null will appear anywhere within the array

{
    "status": "success",

    "error_code": null,

    "matches": [

     {

      "status": "success",

      "error_code": null,

     }
      ,null,

     {}]

}

Apex code:

if(jsonResponse.contains(',null,'))

{

  jsonResponse =  jsonResponse.replaceAll(',null,', ',{"id": ""},');

}

if(jsonResponse.contains('null\\,{'))

{ 

  jsonResponse =  jsonResponse.replaceAll('null\\,{', '{"id": ""},{');

}

if(jsonResponse.contains('null\\]'))

{            

   jsonResponse =  jsonResponse.replaceAll('null\\]', '{"id": ""}]');

}

Please guide me on how to replace null with array #Json #Apex #Trailhead

3 Answers 3

2

Try something like this instead of manipulating the string directly:

Map<String, Object> data = (Map<String, Object>) JSON.deserializeUntyped(jsonResponse);

List<Object> matches = (List<Object>) data.get('matches');

for(Integer i = 0; i < matches.size(); i++) {
    if(matches[i] == null) {
        matches[i] = new Map<String, String>{'id' => ''};
    }
}

data.put('matches', matches);
String newJsonResponse = JSON.serialize(data);
0
1

Do not manipulate the string. Deserialize it and remove the null from the list.

The first step is define a custom Apex class to map that response, then you can leverage typed deserialization, finally you can loop over the list of matches and remove null objects

ResultWrapper result = (ResultWrapper) JSON.deserialize(jsonResponse, ResultWrapper.class);
if (result.matches != null) {
    for (Integer i = result.matches.size() - 1; i >= 0; i--) {
        // remove both null and empty objects
        if (result.matches[i] == null || String.isBlank(result.matches[i].status)) {
            result.matches.remove(i);
            // here you could add a new object at the same position if you want
        }
    }
}
System.debug(result);
2
  • I've tried a similar approach but my code is failing with a null exception because the system is excepting an array record but null is there.
    – Pavan tej
    Commented Aug 18, 2023 at 11:25
  • @Pavantej please provide more detail (the actual code) about the null pointer exception, so I could help with the debug/fix. Anyway in my code I checked for the possible null value based on the question's code.
    – RubenDG
    Commented Aug 18, 2023 at 12:25
-2
public class Match {
    public String status;
    public String error_code;
}

public class JsonResponse {
    public String status;
    public String error_code;
    public List<Match> matches;
}

public static void replaceNullMatches(String jsonString) {
    JsonResponse response = (JsonResponse) JSON.deserialize(jsonString, JsonResponse.class);
    
    for (Integer i = 0; i < response.matches.size(); i++) {
        if (response.matches[i] == null) {
            Match defaultMatch = new Match();
            defaultMatch.status = 'default_status';
            defaultMatch.error_code = 'default_error';
            response.matches[i] = defaultMatch;
        }
    }

    // If you want to get updated JSON string back:
    String updatedJsonString = JSON.serialize(response);
    System.debug(updatedJsonString);
}

String jsonString = '{ "status": "success", "error_code": null, "matches": [ { "status": "success", "error_code": null }, null, {} ] }';
replaceNullMatches(jsonString);
1
  • 2
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Aug 18, 2023 at 11:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .