2

I'm trying to do the same I accomplish with postman but with Apex and I'm not being able to do so:

I need to send a POST request to this example endpoint:

https://cccccccccccccc/api_jsonrpc.php

This is what I've done so far:

First I've copied the json here: http://json2apex.herokuapp.com/

wich gave me this class:

public class JSON2Apex {

    public String jsonrpc;
    public String method;
    public Params params;
    public Integer id;
    public Object auth;

    public class Params {
        public String user;
        public String password;
    }

    
    public static JSON2Apex parse(String json) {
        return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
    }
}

Then I've pasted that generated class as an inner class of my class (i've read it had to be done like this but I was getting strange errors so I built it apart, not as an inner class).

Then, I understand I need to use that generated class to parse my json and send it in the body of my post request but this is not working, I get this error:

Method does not exist or incorrect signature: void setBody(JSON2Apex) from the type System.HttpRequest

I undestand the error but I don't understand how to solve it. Any help or example would be more than valuable sience I've been googleling for a while now and can't understand it.

public class SendingZabbixServices {
    
    public void basicAuthCallout(){
        HttpRequest req = new HttpRequest();
        String endpoint = 'https://cccccccccccccc/api_jsonrpc.php';
        String method = 'POST';
        String jsonString = '{'+
            '   \"jsonrpc\": \"2.0\",'+
            '   \"method\": \"user.login\",'+
            '   \"params\": {'+
            '       \"user\": \"xxxxxx\",'+
            '       \"password\": \"xxxxxxxxxx\"'+
            '   },'+
            '   \"id\": 1,'+
            '   \"auth\": null'+
            '}';


        JSON2Apex obj = JSON2Apex.parse(jsonString);
       
        req.setBody(body);
        req.setEndpoint(endpoint);
        req.setMethod(method);

This is the json I'm trying to send in the body of the post request:

{
   "jsonrpc": "2.0",
   "method": "user.login",
   "params": {
       "user": "xxxxxx",
       "password": "xxxxxxx"
   },
   "id": 1,
   "auth": null
} 
4

As the documentation states, setBody accepts a String argument. In this case, you need to serialize the model.

JSON2Apex payload = new JSON2Apex(...);
request.setBody(JSON.serialize(payload));

I'd recommend you also rename JSON2Apex to something more specific to what you are working on.

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.