0

I receive this json through a request

{"pay_CCIban":"XXX",
"pay_bic":"YYY",
"pay_names[]":["name one","name two"],
"pay_extid":"extId"}

I'm trying to deserialize it with this class

global class Famrs{
    global class datajsonweb{
       global String pay_CCIban {get; set;}
       global String pay_bic {get; set;}
       global List<String> pay_names {get; set;}
       global String pay_extid {get; set;}
    }
    datajsonweb data = (datajsonweb)JSON.deserialize(requestBody.toString(),datajsonweb.class);
    Integer lstSize = data.pay_names.size(); //I get nullpointer here
    ...
}

I get an attempt to de-reference null object when I try to get the size of the array inside the json, i don't know what I'm doing wrong

Any help?

Thanks in advance

EDIT:

Like sfdcfox says, the "pay_names[]" key in the json needs to be like "pay_names" so I'm trying to do a replaceAll('[]','') but I'm getting: Invalid regex: Unclosed character class. If I try to escape the brackets I get: Illegal string literal.

Is it possible to remove the brackets in the json?

Thanks again

EDIT 2:

Thanks to Jesse Milburn's comment it works.

  • Are you sure that every json object contains data for that field? Or even contains that field? If the field is empty (or doesn't exist) the deserializer will not instantiate an empty list. – AvailableName Feb 26 at 13:23
  • Yes completely sure, I get all data correct except for this: "pay_names[]":["name one","name two"], – Javier Feb 26 at 13:31
  • 1
    Why does your pay_names json variable is called "pay_names[]"? Shouldn't it be "pay_names"? – Martin Lezer Feb 26 at 13:38
  • I think that too, but I receive pay_names[] – Javier Feb 26 at 13:46
  • 2
    \\[\\] should be your escape. – Jesse Milburn Feb 26 at 14:02
6

The [] in your JSON won't work. The parser would try to map this to an apex variable named pay_names[]. This is not a valid Apex identifier. Valid identifiers in Apex must start with a letter, can only include letters, numbers, and underscores, can't have two consecutive underscores, and can't be certain reserved keywords. JSON.deserialize does not automatically map things like [] to the nearest valid identifier.

In order to use a JSON class, your JSON would need to be:

{"pay_CCIban":"XXX",
"pay_bic":"YYY",
"pay_names":["name one","name two"],
"pay_extid":"extId"}

If you want to use the JSON exactly as is, use an explicit parser, or use JSON.deserializeUntyped, or JSON.Parser.

| improve this answer | |
  • I think that too, I'm trying now to make a replaceAll('[]','') to remove the brackets in pay_names but I'm getting invalid regex: Unclosed character class near index 2 ].... Updated question – Javier Feb 26 at 13:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.