preparing Json Object for HttpClient Post method - c#

I am trying to prepare a JSON payload to a Post method. The server fails unable to parse my data. ToString() method on my values would not convert it to JSON correctly, can you please suggest a correct way of doing this.
var values = new Dictionary<string, string>
{
{
"type", "a"
}
, {
"card", "2"
}
};
var data = new StringContent(values.ToSttring(), Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
var response = client.PostAsync(myUrl, data).Result;
using (HttpContent content = response.content)
{
result = response.content.ReadAsStringAsync().Result;
}

You need to either manually serialize the object first using JsonConvert.SerializeObject
var values = new Dictionary<string, string>
{
{"type", "a"}, {"card", "2"}
};
var json = JsonConvert.SerializeObject(values);
var data = new StringContent(json, Encoding.UTF8, "application/json");
//...code removed for brevity
Or depending on your platform, use the PostAsJsonAsync extension method on HttpClient.
var values = new Dictionary<string, string>
{
{"type", "a"}, {"card", "2"}
};
var client = new HttpClient();
using(var response = client.PostAsJsonAsync(myUrl, values).Result) {
result = response.Content.ReadAsStringAsync().Result;
}

https://www.newtonsoft.com/json use this.
there are already a lot of similar topics.
Send JSON via POST in C# and Receive the JSON returned?

values.ToString() will not create a valid JSON formatted string.
I'd recommend you use a JSON parser, such as Json.Net or LitJson to convert your Dictionary into a valid json string. These libraries are capable of converting generic objects into valid JSON strings using reflection, and will be faster than manually serialising into the JSON format (although this is possible if required).
Please see here for the JSON string format definition (if you wish to manually serialise the objects), and for a list of 3rd party libraries at the bottom: http://www.json.org/

Related

Posting data with FormUrlEncoded OR Json in web api

I have created generic method from which we are posting data to web apis. And while making posting I am serializing the data to json. Below is my generic method.
public HttpResponseMessage GetData<T>(T parm, string url) where T : class
{
try
{
var client = new HttpClient();
var result = client.PostAsync(url, SerializeData<T>(parm));
result.Wait();
if (result.Result.IsSuccessStatusCode)
{
// Do something
}
}
catch (Exception ex)
{
throw ex;
}
return default(HttpResponseMessage);
}
private StringContent SerializeData<T>(T obj)
{
string mediaType = "application/json";
string content = JsonConvert.SerializeObject(obj, formatter);
return new StringContent(content, Encoding.UTF8, mediaType);
}
This work fine if I pass the class object from the caller method Like
var result = service.GetData<MyClass>(myclassobj,url);
However, for some urls by passing the class object is not working. So, we have written another method where we posting the data in FormUrlEncodedContent format like below and it works fine.
var Parameters = new Dictionary<string, string> { { "Key1", "some value" }, { "Key2", "another value" } };
var EncodedContent = new FormUrlEncodedContent(Parameters);
var postTask = _client.PostAsync(url, EncodedContent);
I have tried to send FormUrlEncoded data to JSON method and by changing the Media Type also. But not able to properly serialized it. The apis/services we are consuming are from third party providers.
So my question is what changes are needed in the method which will work with all formats Like JSON, FormUrlEncodedContent etc.
Also, does it depend on how apis are written to which they will work only with specific formats like JSON, FormUrlEncodedContent etc.
Basically I am trying to keep one generic method which will support all formats.
Any help on this appreciated !

Move Json Object From One Site To Another

I have two project in asp.net webforms with different url. I need to move c# object from one to the other. I tried to serialize it to JSON with JavaScriptSerializer and move it as parameter in the url, but I don't want the client would see the json
A a = new A()
{
val = 1,
val1 = "very long string"
};
var jsonSerialiser = new JavaScriptSerializer();
string data = jsonSerialiser.Serialize(a);
Response.Redirect(service.RedirectToCheckout("http://localhost:44316/PageOnOtherSite.aspx?data=" + data));
Any ideas?
simple post request using HttpClient
using(var client = new HttpClient())
{
response = await httpClient.PostAsync(uri, new StringContent(data));
{

Passing a nested Dictionary to web API

I am using a Post method to send data to a web API. Something like this:
string apiUrl = serviceAddress;
var client = new HttpClient();
var DObject = new Dictionary<string, string>()
{
{"UserId", UserID},
{"Type", "109" },
{"Id", templateID},
{"Subject", subjectofEmail},
{"Data", #"'Name','Payman','Family','Payman'"}
};
var content = new FormUrlEncodedContent(DObject);
var response = client.PostAsync(apiUrl, content);
The problem is that, the Data object is also a dictionary. So, I have problem sending data. What is the solution?

Dictionary and object to web service content type string

I have Dictionary with values how to convert them to string of format application/json and application/x-www-form-urlencoded simplest standard way:
var values = new Dictionary<string, string>
{
{"id", "1"},
{"amount", "5"}
};
The same question regarding class object with the same fields:
class values
{
public String id { get; set; }
public string amount { get; set; }
}
simple way is using json.NET library in order to post the data. you can convert your object to application/json like this:
var jsonString = JsonConvert.SerializeObject(values);
then post it to your service like this:
private static T Call<T>(string url, string body)
{
var contentBytes = Encoding.UTF8.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 60 * 1000;
request.ContentLength = contentBytes.Length;
request.Method = "POST";
request.ContentType = #"application/json";
using (var requestWritter = request.GetRequestStream())
requestWritter.Write(contentBytes, 0, (int)request.ContentLength);
var responseString = string.Empty;
var webResponse = (HttpWebResponse)request.GetResponse();
var responseStream = webResponse.GetResponseStream();
using (var reader = new StreamReader(responseStream))
responseString = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(responseString);
}
It's not clear from your question if you want to manually serialize your dictionary or object and then send it using a custom way or if you would like to automatically serialize and send them to a web service.
The manual way:
Json
PM > Install-Package Newtonsoft.Json
Json.NET natively supports dictionary to Json object and, of course, object to json object serialization. You simply install it and than serialize using:
var jsonString = JsonConvert.SerializeObject(values); // values can be Dictionary<string, Anything> OR an object
Result:
{
"id": "1",
"amount", "5"
}
Form URL encoded
The cleanest way is to use the .NET built-in utility HttpUtility.ParseQueryString (which also encodes any non-ASCII character):
var nvc = HttpUtility.ParseQueryString("");
foreach(var item in values)
nvc.Add(item.Key, item.Value);
var urlEncodedString = nvc.ToString();
Result:
id=1&amount=5
Please note that there is no direct way to serialize an object into a Form URL encoded string without adding its members manually, e.g.:
nvc.Add(nameof(values.id), values.id);
nvc.Add(nameof(values.amount), values.amount);
The automatic way:
Everything is simpler if you just use HttpClient:
PM > Install-Package Microsoft.AspNet.WebApi.Client
Json
You may need to also use HttpClientExtensions extension methods for automatic Json serialization (without it you need to serialize it manually as shown above):
using (var client = new HttpClient())
{
// set any header here
var response = await client.PostAsJsonAsync("http://myurl", values); // values can be a dictionary or an object
var result = await response.Content.ReadAsAsync<MyResultClass>();
}
Form URL encoded
using (var client = new HttpClient())
{
using (var content = new FormUrlEncodedContent(values)) // this must be a dictionary or a IEnumerable<KeyValuePair<string, string>>
{
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var response = await client.PostAsync(url, content);
var result = await response.Content.ReadAsAsync<MyResultClass>();
}
}
This way you may serialize dictionaries directly. Again for objects you need to convert them manually as shown above.

Pass associative array to PHP API from C#

I am working in calling PHP API from c#. But, my problem arise when I have to pass associative array to API. I don't know exact implementation of PHP associative array in C# but I have used dictionary. It didn't works.
I have been using RestSharp to call API.
Code Implemenation:
var client = new RestClient(BaseUrl);
var request = new RestRequest(ResourceUrl, Method.POST);
IDictionary<string,string> dicRequeset = new Dictionary<string, string>
{
{"request-id", "1234"},
{"hardware-id", "CCCCXXX"},
};
request.AddParameter("request", dicRequeset);
var response = client.Execute(request);
var content = response.Content;
PHP API Implementation(Short):
* Expected input:
* string request[request-id,hardware-id]
* Return:
* code = 0 for success
* string activation_code
*/
function activate()
{
$license = $this->checkFetchLicense();
if (!$license instanceof License) return;
$response = $license->activate((array)$this->_request->getParam('request'));
}
Can someone help me to pass array to PHP API from C#?
Maybe adding the pairs makes differences in conventions in C# and PHP? Have you tried using Add?
IDictionary<string,string> dicRequeset = new Dictionary<string, string>();
dicRequeset.Add("request-id", "1234");
dicRequeset.Add("hardware-id", "CCCCXXX");
Or using indexer?
dicRequeset["request-id"] = "1234";
dicRequeset["hardware-id"] = "CCCXXX";
Or the best I can imagine is JSON as it is designed for the purpose of transmission.
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new {request-id = "1234", hardware-id = "CCCXXX"});
The problem in the third variant despite I marked it as the best, might be that the PHP API may not decode the JSON string, because it might not be designed that way. But in general purpose JSON is meant to solve that kind of problems.
Though late post but I've solved this problem by using following approach :
var request = new RestRequest(ResourceUrl, Method.POST);
request.AddParameter("request[request-id]", hardwareId);
request.AddParameter("request[hardware-id]", hardwareId);
if I guess right, the AddParameter method of RestSharp doesn't automatically serialize an object to json thus insteadly just calls the object's toString method.
So try to get a JSON.net library and make the json encoding manually,
IDictionary<string,string> dicRequeset = new Dictionary<string, string>
{
{"request-id", "1234"},
{"hardware-id", "CCCCXXX"},
};
var jsonstr = JsonConvert.SerializeObject(dicRequeset);
request.AddParameter("request", jsonstr);
this should work.

Categories