JSON.deserializeUntyped turns JSON text into Apex values. JSON.serialize goes the
other way: it takes an Apex value and returns the JSON text for it. That is the call
you need when you build the body of a request.
Map<String, Object> payload = new Map<String, Object>();
payload.put('username', username);
payload.put('password', password);
String body = JSON.serialize(payload);
The map becomes a JSON object, the keys are the ones you put in, and the values keep
the type they had. Send the text with request.setBody(body);.
The order of the keys in the text is not the order you put them in. A map filled with
zebra, alpha and middle comes back as middle, alpha, zebra. Never compare
serialized text with an expected string, and never build an expected string by hand:
compare the parsed values instead.
A value that carries a quote comes back with the quote escaped, and a newline or a
backslash is escaped too. This is the reason to serialize rather than to join strings
together: a body built by hand falls apart the moment one value holds a quote.
JSON.serialize(value, true) drops the null fields of a class instance. It does not
touch a map: a null value in a map stays in the text. The flag is named
suppressApexObjectNulls and it means what it says.
Serializing a record adds an attributes object holding the type and the url of the
record, plus the Id. When you send data to another service, build a map of the fields
you want to send instead of serializing the record itself.
Content-Type header. The service cannot read the body and answers