2

I am trying to use public REST API that that has hyphens in variable names. Apex does not support variable names with hyphens. JSON2Apex tool generates kind of strange class as well.

I was facing this issue before but in reverse (JavaScript library needed certain variables that had hyphens in them).

What is the best practice here?

Sample JSON below:

{
  "scans": {
    "Bkav": {
      "detected": true,
      "version": "1.3.0.6979",
      "result": "DOS.EiracA.Trojan",
      "update": "20150627"
    },
    "MicroWorld-eScan": {
      "detected": true,
      "version": "12.0.250.0",
      "result": "EICAR-Test-File",
      "update": "20150628"
    }
  },
  "scan_id": "131f95c51cc819465fa1797f6ccacf9d494aaaff46fa3eac73ae63ffbdfd8267-1435525629"
}

1 Answer 1

3

The simple workaround for this to change the string body using string.replace

string jsonbody=httpresponse.getbody();
jsonbody=jsonbody.replace('-eScan','eScan');
//Now use JSON.deserialize();

In your apex class you would have property name as MicroWorldeScan

The above is just a work around but if you want a neater solution to your problem use JSON.deserializeUntyped

Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(jsonbody);

https://gist.github.com/TehNrd/4559623

3
  • Sounds intriguing, but I get System.TypeException: Invalid conversion from runtime type Map<String,ANY> to List<ANY>
    – dzh
    Commented Jun 28, 2015 at 21:44
  • Ok so the whole loop was unnecesary. This worked Map<String,Object> data = (Map<String,Object>)JSON.deserializeUntyped(jsonResponse); system.debug(data.get('total'));
    – dzh
    Commented Jun 28, 2015 at 21:53
  • You can read through documentation on how to use this and parse.. Commented Jun 28, 2015 at 21:56

You must log in to answer this question.

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