TransWikia.com

How can I use a reserved keyword as an identifier in my JSON wrapper class

Salesforce Asked by SFDC_Beginner on November 5, 2021

From salesforce Trying to Create PayPal payment, In Create Payment method request object has Items with Currency like below

  "name": "hat",
            "description": "Brown hat.",
            "quantity": "5",
            "price": "3",
            "tax": "0.01",
            "sku": "1",
            "currency": "USD"

I can’t able to use as a currency in Apex, Identifier name is reserved: currency

@AuraEnabled
public string currency {get;set;}    

Error Identifier name is reserved: currency

One Answer

If you were deserializing, this is a scenario where you'd use untyped deserialization. Since untyped deserialization keeps all of they keys as strings, reserved keywords are not an issue.

Map<String, Object> untypedResult = (Map<String, Object>)JSON.deserializeUntyped(myJSON);

// handling an untyped deserialization involves a lot of casting
String myCurrency = (String)untypedResult.get('currency');

Since you're trying to do the opposite here, and serialize data with a reserved keyword, all you really need to do is the same thing, but in reverse.

That is to say, create a Map<String, Object>, and then serialize that map.

Map<String, Object> objMap = new Map<String, Object>{
    'name' => wrapper.name,
    'description' => wrapper.description,
    ...
    // You'll need to change your wrapper class to use a valid identifier
    //   but, since you're in control of this entire process, you can easily say
    //   "oh yeah, this one particular field needs to be called something else in the
    //   JSON
    'currency' => wrapper.currencyType
};

String myJSON = JSON.serialize(objMap);

I imagine there are other ways to tackle this problem, but this is likely the most straightforward approach.

Answered by Derek F on November 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP