Jinhoon Jeong
Jinhoon Jeong

Reputation: 53

python to c# (about server request)

I need to translate this python code into C#:

messages = { "to" :"PhoneNumber" }
body = {
    "type" : "SMS",
    "contentType" : "COMM",
    "from" : "PhoneNumber2",
    "subject" :"subject",
    "content" : "Hell world",
    "messages" : [messages]
}
body2 = json.dumps(body)
headers = {
    'Content-Type': 'application/json; charset=utf-8',
    'X-ncp-apigw-timestamp': timestamp,
    'x-ncp-iam-access-key': access_key,
    'x-ncp-apigw-signature-v2': make_signature(uri, access_key)
    }

res = requests.post(apiUrl, headers=headers, data=body2)

res.request
res.status_code
res.raise_for_status()

print(res.json())

So I've tried :

    public class themessage
    {
        public string to;
    }
    public class body
    {
        public string type;
        public string contentType;
        public string from;
        public string subject;
        public string content;
        public themessage messages;
    }


            var obj = new body
            {
                type = "SMS",
                contentType = "COMM",
                from = "PN",
                subject = "subject",
                content = "Hell World",
                messages = new themessage
                {
                    to = "PN"
                }
            };


            var client = new RestClient(apiUrl);
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json; charset=utf-8");
            request.AddHeader("X-ncp-apigw-timestamp", timestamp);
            request.AddHeader("x-ncp-iam-access-key", accessKey);
            request.AddHeader("x-ncp-apigw-signature-v2", test);
            request.AddJsonBody(obj); // **this is where I'm concerning part**
            IRestResponse response = client.Execute(request);

But, as you expected, failed to post with error message of "Not requested format" something.

Did I something wrong when making JsonBody? or posting process?

Thanks for all answers in advance!

Upvotes: 1

Views: 100

Answers (1)

Markus Deibel
Markus Deibel

Reputation: 1329

Following my last comment on the IRestRequest interface, your class hierarchy should look similar to

public class themessage
{
    public string to;
}

public class body
{
    public string type;
    public string contentType;
    public string from;
    public string subject;
    public string content;
    public themessage[] messages; // <- Array here
}

and the object you create with it will be something like

var obj = new body
{
    type = "SMS",
    contentType = "COMM",
    from = "PN",
    subject = "subject",
    content = "Hell World",
    messages = new themessage[] { new themessage{to = "PN"} }
};

The code for the RestClient and RestRquest stays as it is.

Upvotes: 1

Related Questions