This is kind of new to me - I need to make apex http post call and to set the body as json. My json is constructed in the following way:

{ "request": "request", "ID": "reqId", "getString": { "StringOne": "12345", "StringTwo": "67891", } }

Can you please help me with building this Json inside my apex class ? I'm a bit stuck in the part of the getString - I didn't understand what is the best way to add new object with fields - and set the fields name inside this object.

Thanks !!


This what iv'e done so far ..

JSONGenerator gen = JSON.createGenerator(true);
        gen.writeStringField('request', 'request');
        gen.writeStringField('ID', 'reqId');

        String jsonS = gen.getAsString();

1 Answer 1


Don't use JSONGenerator unless you're porting legacy Java code that already uses it. It's more efficient to just use a Map:

String jsonString = JSON.serialize(
  new Map<String, Object> {
    'request' => 'request',
    'ID' => 'reqId',
    'getString' => new Map<String, Object> {
      'StringOne' => '12345',
      'StringTwo' => '67891'

You must log in to answer this question.

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