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();

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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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