I am using a json string like this in a test class.


Now instead of hard coding id, I want to use a variable named prdId.

How can I do this? I tried putting prdId there, it says,

System.JSONException: Unexpected character ('p' (code 112)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at [line:1, column:9]

1 Answer 1


Omitting the rest of the structure for brevity, you can do something like the following:

'[{"id": "' + prId + '"}]`

I tend to prefer creating a class to represent the structure and then serialize that.

class MyObject
    Id id;
    String name;
    DateRange dateRange;
class DateRange
    String startDate, endDate;

Then in your test:

MyObject instance = new MyObject();
instance.id = prId;
instance.name = 'abc123';
instance.dateRange = new DateRange();
instance.dateRange.startDate = '2020-02-17';
instance.dateRange.endDate = '2020-02-26';
String myJSON = JSON.serialize(instance);
  • There should be \ to escape " in the string. Mar 3, 2016 at 20:00
  • 1
    @VigneshwaranG You don't need to escape double quotes in Apex, it's wrapped in single quotes.
    – Adrian Larson
    Mar 3, 2016 at 20:01

You must log in to answer this question.

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