REST api with C#.NET complex json data in body posting

Maruf Hossain

I want to use sms gateway in my app. that's why I've contact with an operator and the operator give me a api format.

URL: https://ideabiz.lk/apicall/smsmessaging/v2/outbound/3313/requests

Request header

Content-Type: application/json 
Authorization: Bearer [access token] 
Accept: application/json

Body

{
    "outboundSMSMessageRequest": {
        "address": [
            "tel:+94771234567"
        ],
        "senderAddress": "tel:12345678",
        "outboundSMSTextMessage": {
            "message": "Test Message"
        },
        "clientCorrelator": "123456",
        "receiptRequest": {
            "notifyURL": "http://128.199.174.220:1080/sms/report",
            "callbackData": "some-data-useful-to-the-requester"
        },
        "senderName": "ACME Inc."
    }
}

Now, I've code it :

RestClient client = new RestClient(@"https://ideabiz.lk/");
RestRequest req = new RestRequest(@"apicall/smsmessaging/v2/outbound/3313/requests", Method.POST);

req.AddHeader("Content-Type", @"application/json");
req.AddHeader("Authorization", @"Bearer " + accessToken.ToString());
req.AddHeader("Accept", @"application/json");

string jSon_Data = @"{'outboundSMSMessageRequest': {'address': ['tel:+94768769027'],'senderAddress': 'tel:3313','outboundSMSTextMessage': {'message': 'Test Message : " + System.DateTime.Now.ToString() + "'},'clientCorrelator': '123456','receiptRequest': {'notifyURL': 'http://128.199.174.220:1080/sms/report','callbackData': 'some-data-useful-to-the-requester'},'senderName': ''}}";


JObject json = JObject.Parse(jSon_Data);
req.AddBody(json);

IRestResponse response = client.Execute(req);
string x = response.Content.ToString();
Console.WriteLine(x.ToString());

When i execute this program, in the line

req.AddBody(json);

my system crash and give error message that:

An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll

How can i post complex JSON by using C#.NET ?

dbc

You have two problems here:

  1. You need to set RequestFormat = DataFormat.Json before the call to AddBody:

        req.RequestFormat = DataFormat.Json;
        req.AddBody(json);
    

    Without setting the parameter, RestSharp tries to serialize the JObject to XML and falls into an infinite recursion somewhere -- most likely trying to serialize JToken.Parent.

  2. The more recent versions of RestSharp no longer use Json.NET as their JSON serializer:

    There is one breaking change: the default Json*Serializer* is no longer 
    compatible with Json.NET. To use Json.NET for serialization, copy the code 
    from https://github.com/restsharp/RestSharp/blob/86b31f9adf049d7fb821de8279154f41a17b36f7/RestSharp/Serializers/JsonSerializer.cs 
    and register it with your client:
    
    var client = new RestClient();
    client.JsonSerializer = new YourCustomSerializer();
    

    RestSharp's new built-in JSON serializer doesn't understand JObject so you need to follow the instructions above if you are using one of these more recent versions, Create:

    public class JsonDotNetSerializer : ISerializer
    {
        private readonly Newtonsoft.Json.JsonSerializer _serializer;
    
        /// <summary>
        /// Default serializer
        /// </summary>
        public JsonDotNetSerializer() {
            ContentType = "application/json";
            _serializer = new Newtonsoft.Json.JsonSerializer {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling = NullValueHandling.Include,
                DefaultValueHandling = DefaultValueHandling.Include
            };
        }
    
        /// <summary>
        /// Default serializer with overload for allowing custom Json.NET settings
        /// </summary>
        public JsonDotNetSerializer(Newtonsoft.Json.JsonSerializer serializer){
            ContentType = "application/json";
            _serializer = serializer;
        }
    
        /// <summary>
        /// Serialize the object as JSON
        /// </summary>
        /// <param name="obj">Object to serialize</param>
        /// <returns>JSON as String</returns>
        public string Serialize(object obj) {
            using (var stringWriter = new StringWriter()) {
                using (var jsonTextWriter = new JsonTextWriter(stringWriter)) {
                    jsonTextWriter.Formatting = Formatting.Indented;
                    jsonTextWriter.QuoteChar = '"';
    
                    _serializer.Serialize(jsonTextWriter, obj);
    
                    var result = stringWriter.ToString();
                    return result;
                }
            }
        }
    
        /// <summary>
        /// Unused for JSON Serialization
        /// </summary>
        public string DateFormat { get; set; }
        /// <summary>
        /// Unused for JSON Serialization
        /// </summary>
        public string RootElement { get; set; }
        /// <summary>
        /// Unused for JSON Serialization
        /// </summary>
        public string Namespace { get; set; }
        /// <summary>
        /// Content type for serialized content
        /// </summary>
        public string ContentType { get; set; }
    }
    

    And then do:

        RestRequest req = new RestRequest(@"apicall/smsmessaging/v2/outbound/3313/requests", Method.POST);
        req.JsonSerializer = new JsonDotNetSerializer();
    

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

POSTing complex JSON to ASP.NET Core Controller

From Dev

Posting complex form data to a RESTful API with AngularJS and Express

From Java

Bad request with response code 400, when posting json data to rest api using okHttp 4.*

From Dev

Bad request with response code 400, when posting json data to rest api using okHttp 4.*

From Dev

Posting Ruby data in JSON format with Net/http

From Dev

posting HTTP-BODY data with Needle api in node.js

From Dev

HttpPost Posting Complex JSONObject in the Body of the Request

From Dev

Writing a REST API for Complex Nested Data

From Dev

Writing a REST API for Complex Nested Data

From Dev

Trying to convert a CSV into JSON in python for posting to REST API

From Dev

Java Rest Jersey : Posting multiple types of data (File and JSON)

From Dev

jQuery get request with json body to a REST api

From Dev

Posting a complex object with ASP.NET WebAPI

From Dev

How to deserialize a complex separated ("Column"/"Data") json to c# object using json.net

From Dev

How to deserialize a complex separated ("Column"/"Data") json to c# object using json.net

From Dev

Posting form data with Nodejs and body-parser

From Dev

Post Json Data to Rest API

From Dev

Sending JSON data to rest api

From Dev

Post json data in body to web api

From Dev

Deserialize complex JSON data in C#

From Dev

AngularJS - Posting data to API is not working

From Dev

Posting data with json in xcode 6.0.1

From Dev

JSON formatted data posting to an endpoint

From Dev

Spring REST: Get JSON data from Request body in addition to entity

From Dev

Posting to REST api using Java, specifically Android

From Dev

Spring REST API for posting jar file

From Dev

Posting form submissions with the KOBO REST API

From Dev

Error posting json parameter to REST service

From Dev

POSTing to a collection association using Spring Data Rest

Related Related

  1. 1

    POSTing complex JSON to ASP.NET Core Controller

  2. 2

    Posting complex form data to a RESTful API with AngularJS and Express

  3. 3

    Bad request with response code 400, when posting json data to rest api using okHttp 4.*

  4. 4

    Bad request with response code 400, when posting json data to rest api using okHttp 4.*

  5. 5

    Posting Ruby data in JSON format with Net/http

  6. 6

    posting HTTP-BODY data with Needle api in node.js

  7. 7

    HttpPost Posting Complex JSONObject in the Body of the Request

  8. 8

    Writing a REST API for Complex Nested Data

  9. 9

    Writing a REST API for Complex Nested Data

  10. 10

    Trying to convert a CSV into JSON in python for posting to REST API

  11. 11

    Java Rest Jersey : Posting multiple types of data (File and JSON)

  12. 12

    jQuery get request with json body to a REST api

  13. 13

    Posting a complex object with ASP.NET WebAPI

  14. 14

    How to deserialize a complex separated ("Column"/"Data") json to c# object using json.net

  15. 15

    How to deserialize a complex separated ("Column"/"Data") json to c# object using json.net

  16. 16

    Posting form data with Nodejs and body-parser

  17. 17

    Post Json Data to Rest API

  18. 18

    Sending JSON data to rest api

  19. 19

    Post json data in body to web api

  20. 20

    Deserialize complex JSON data in C#

  21. 21

    AngularJS - Posting data to API is not working

  22. 22

    Posting data with json in xcode 6.0.1

  23. 23

    JSON formatted data posting to an endpoint

  24. 24

    Spring REST: Get JSON data from Request body in addition to entity

  25. 25

    Posting to REST api using Java, specifically Android

  26. 26

    Spring REST API for posting jar file

  27. 27

    Posting form submissions with the KOBO REST API

  28. 28

    Error posting json parameter to REST service

  29. 29

    POSTing to a collection association using Spring Data Rest

HotTag

Archive