1

I am getting following payload and am not sure how to deserialize it properly. Please note: I already used the JSON2Apex and the provided code did not work for me. Also, the actual payload is pretty big so I cannot keep using if-else to check token names and store values in local string and assigning it to fields . I have a dynamic framework to map payload variables to SF fields. hence its a no to JSONtoApex.

{
    "payload.deal_id": "158968902749",
    "payload.delivery_date": "2017-03-08",
    "payload.deal": "Test Deal",
    "payload.revenue": 257800967,
    "payload.numValue": 0,
    "payload.anotherValue": 35
}

using the variable name as it is,

public String payload.deal_id {get;set;}

throws an error ....

Unexpected token '.'

Let me know if any one has an idea. Thanks!

1
  • If you already have a proper mapping mechanism, you shouldn't need a huge if-else structure, just enough to pick out the object type.
    – sfdcfox
    Oct 5, 2018 at 18:01

1 Answer 1

5

The three basic fixes to any invalid identifier in your JSON keys are:

  1. Deserialize untyped (Map<String, Object> in this case)

    Map<String, Object> data = (Map<String, Object>)JSON.deserializeUntyped(payload);
    String deal_id = (String)data.get('payload.deal_id');
    
  2. Use string replacement.

    payload = payload.replaceAll('"payload.', '');
    
  3. Roll your own JSON parser.

I strongly prefer the first option.

4
  • String deal_id = data.get('payload.deal_id'); should be String deal_id = (String) data.get('payload.deal_id'); as we cannot assign Object to String.
    – brahma
    Oct 5, 2018 at 18:10
  • @brahmajitammana yes. you are correct. Else it will throw illegal assignment.
    – login2ak
    Oct 5, 2018 at 18:22
  • 2
    +1, but that string replacement would break json. instead: payload = payload.replaceAll('"payload\\.(.+?)":', '"$1":');
    – sfdcfox
    Oct 5, 2018 at 19:03
  • Actually I tested it on the very payload in the OP and it worked just fine.
    – Adrian Larson
    Oct 5, 2018 at 20:16

You must log in to answer this question.

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