2

This question already has an answer here:

Is there any way to set the name of the serializable field? I'm trying to work with JIRA webhooks and I ran into an issue where their request package contains a field that is a protected keyword in Apex:

JSON

{
    "toString": "A new summary.",
    "to": null,
    "fromString": "What is going on here?????",
    "from": null,
    "fieldtype": "jira",
    "field": "summary"
}

Class

public class Item
{
    public string toString { get; set; }
    public string to { get; set; }
    public string fromString { get; set; }
    public string from { get; set; }
    public string fieldtype { get; set; }
    public string field { get; set; }
}

When I try to save this I get an error:

unexpected token: 'from'

C# has a annotation you can add to set the serializable name: [JsonProperty(PropertyName = "FooBar")] Not sure if apex has anything similar.

marked as duplicate by NSjonas, Boris Bachovski, Vamsi Krishna, Eric, Samuel De Rycke Aug 7 '15 at 8:14

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3

Kind of obvious/hacky but I've always dealt with these sorts of problems (see also deserialising from a source which contains SF keywords) by search+replace on the JSON string. So

public class Item
{
    public string toString { get; set; }
    public string to { get; set; }
    public string fromString { get; set; }
    public string wantsToBeFrom { get; set; }
    public string fieldtype { get; set; }
    public string field { get; set; }
}

String jsonOut = JSON.serialize(myItems);
jsonOut = jsonOut.replaceAll('"wantsToBeFrom":','"from":');

The approved way would be to use JSONGenerator to create the output yourself with whatever field name mapping you want.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_json_jsongenerator.htm

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