Send array post RestSharp?
Dictionary, List<> is not compatibile ?
public class Test
{
public string key { get; set; }
public string viewType { get; set; }
public string module { get; set; }
public string method { get; set; }
public Dictionary<string, string> parameters { get; set; }
}
My class init.
Test t = new Test();
t.key = "xxxxxxxxxxxxxxxxxx";
t.viewType = "json";
t.module = "test";
t.method = "test";
t.parameters = new Dictionary<string,string>();
t.parameters.Add("p1", "data1");
Send data request
IRestResponse response = restClient.Execute<Test>(restRequest);
Send is debbuger:
[JSON]
-request
module: "test"
method: "test"
parameters:"System.Collections.Generic.Dictionary`2[System.String,System.String]"
Who RestSharp create ? ? Send Array options object ?
$postData = array(
'key' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'viewType' => 'json',
'module' => 'test',
'method' => 'test',
[options] => stdClass Object
(
[name] => 'ADIDAS'
)
);
I found this in the documentation:
To add all properties for an object as parameters, use AddObject(). To
add a file for upload, use AddFile() (request will be sent as
multipart encoded form). To include a request body (like XML or JSON),
use AddBody();
So because you are using restRequest.AddObject(), RestSharp uses the value of t.parameters.ToString() instead of serializing to JSON.
Fix: use restRequest.AddBody(t) instead. You also have to specify the content type.
request.RequestFormat = DataFormat.Json;
request.AddBody(t);
RestClient restClient = new RestClient("https:");
RestRequest restRequest = new RestRequest(Method.POST);
Test t = new Test();
t.key = ac.Password;
t.viewType = "json";
t.module = "hello";
t.method = "hello";
t.parameters = new Dictionary<string,string>();
t.parameters.Add("wddwdw", "ddd");
restRequest.AddObject(t);
IRestResponse response = restClient.Execute<Test>(restRequest);
Related
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!
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.
Newbie in this so sorry for the mistakes.
I have a C# app that is running and calling python functions. the functions is being called using POST method. In addition, I would like that this call will reply from python to C# object which include 4 arrays. I successfully did passing a simple string but when I am trying to pass an object, it doesnt work. Here is the code:
C# caller side
public class RootObject
{
public Array b1 { get; set; }
public Array cl { get; set; }
public Array sc { get; set; }
}
public static List<RootObject> post(string path, int Port)
{
var client = new RestClient("http://localhost:" +
Port.ToString());
var request = new RestRequest("/postmethod", Method.POST);
request.AddHeader("content-type", "application/form-data");
request.AddFile("file", path);
IRestResponse response = client.Execute(request);
var json = response.Content;
var content = response.Content; // raw content as string
List<RootObject> r;
r = JsonConvert.DeserializeObject<List<RootObject>>(json);
return r;
}
Python side
class myscoresobj:
def __init__(self):
self.b1
self.cl
self.sc
#app.route('/postmethod', methods=['POST'])
def index():
if 'file' not in request.files:
return "file not found"
file = request.files['file']
contents = file.read()
....
myscoresobj = worker(input_q, output_q)
return str(myscoresobj )
Any way how to solve this?
i am quite new to Json, i have a program which makes a put request with some json data.
i need to make the equivelant of this: { "project": { "date_closed":"2017-01-05"} }
and this is my code i need to adapt..
object instructionData = new { date_closed = DateTime.Now.ToString("yyyy-MM-dd") };
var instructionString = JsonConvert.SerializeObject(instructionData);
StringContent instruction = new StringContent(instructionString, Encoding.UTF8, "application/json");
which is currently more than i can seem to figure out...
i've looked at some converters, which just creates classes. And those i don't really know what to do with..
Hope there is someone willing to help.
Edit
i am creating a response which is being sent.
var response = instructions.GetPutResponse(instructions.GetCleanUpProjectsRequestUrl(projectId), instructions.GetJsonInstructions(instructionData), client);
GetPutResponse method:
public HttpResponseMessage GetPutResponse(string requestUrl, HttpContent httpContent, HttpClient client)
{
return client.PutAsync(requestUrl, httpContent).Result;
}
public class Project
{
public string date_closed { get; set;}
}
public class MyClass
{
public Project project { get; set;}
}
var obj = new MyClass();
obj.project = new Project();
obj.project.date_closed = DateTime.Now.ToString("yyyy-MM-dd");
var instructionString = JsonConvert.SerializeObject(obj);
Like one of comments above suggests using string concatenation which seems fair approach however if you don't want to go that route then you can use following snippet to achieve what you want. Replace below line
object instructionData = new { date_closed = DateTime.Now.ToString("yyyy-MM-dd") };
with
var instructionData = new { projects = new { date_closed = DateTime.Now.ToString("yyyy-MM-dd") } };
We have got a Odata response as below:
"{\r\n \"#odata.context\":\"http://localhost/ApplicationService/model/$metadata#Edm.String\",\"value\":\"{\\\"Messages\\\":[\\\"message 1\\\",\\\"message 2\\\",\\\"message 3\\\",\\\"message 4\\\"],\\\"IsValidEntity\\\":false}\"\r\n}"
Now say we have a class:
public class myValidationResult
{
public myValidationResult()
{
Messages = new List<string>();
}
public List<string> Messages { get; set; }
public bool IsValidEntity { get; set; }
}
This class used in MyOdataController class as below:
public class MyODataController : ODataController
{
[Authorize(Roles = "Admin")]
public async Task<IHttpActionResult> Post(T entity)
{
myValidationResult vResult = new myValidationResult();
vResult.Messages.Add("message 1");
vResult.Messages.Add("message 2");
vResult.Messages.Add("message 3");
vResult.Messages.Add("message 4");
vResult.IsValidEntity = false;
var strResult = JsonConvert.SerializeObject(vResult);
var resp = Content(HttpStatusCode.BadRequest, strResult );
return resp;
}
}
For the client Consuming this, we created below Class:
public class OData<T>
{
[JsonProperty("odata.context")]
public string Metadata { get; set; }
public T value { get; set; }
}
In the method where we call the Odata method & store response in 'msg':
var resp = msg.Result.Content.ReadAsStringAsync().Result;
resp is:
"{\r\n \"#odata.context\":\"http://localhost/ApplicationService/model/$metadata#Edm.String\",\"value\":\"{\\\"Messages\\\":[\\\"message 1\\\",\\\"message 2\\\",\\\"message 3\\\",\\\"message 4\\\"],\\\"IsValidEntity\\\":false}\"\r\n}"
var odatares = JsonConvert.DeserializeObject<OData<myValidationResult>>(resp);
But the above line giving error:
Can not convert value\":\"{\\\"Messages\\\":[\\\"message 1\\\",\\\"message 2\\\",\\\"message 3\\\",\\\"message 4\\\"],\\\"IsValidEntity\\\":false} to <.....namespace......>myValidationResult
Please suggest accordingly.
The OData response contains a string, not an instance of myValidationResult. Also, the response looks like it's missing some backslashes. (Are you sure the response shown is exactly what you received from the service?)
You can either fix the serialization of myValidationResult on the service:
// Don't serialize vResult yourself. OData will do it for you.
var resp = Content(HttpStatusCode.BadRequest, vResult );
Or deserialize in two steps as follows.
var data = "{\r\n \"#odata.context\":\"http://localhost/ApplicationService/model/$metadata#Edm.String\",\"value\":\"{\\\"Messages\\\":[\\\"message 1\\\",\\\"message 2\\\",\\\"message 3\\\",\\\"message 4\\\"],\\\"IsValidEntity\\\":false}\"\r\n}";
var outer = Newtonsoft.Json.JsonConvert.DeserializeObject<OData<string>>(data);
var inner = Newtonsoft.Json.JsonConvert.DeserializeObject<myValidationResult>(outer.value);
One more thing: The JsonProperty on OData<T> should be named #odata.context.
In my case the OData response did not contain a string but an object array which contains the data string as its first element. So in this case reading the data should look like this:
var outer = Newtonsoft.Json.JsonConvert.DeserializeObject<OData<object[]>>(data);
var inner = Newtonsoft.Json.JsonConvert.DeserializeObject<myValidationResult>(outer.value[0].ToString());
i've an xml from some api :
<auditypes>
<auditype code="a" description="aaa"/>
<auditype code="b" description="bbb"/>
<auditype code="c" description="ccc"/>
<auditype code="d" description="ddd"/>
<auditype code="e" description="eee"/>
</auditypes>
and mapping as object in C# class :
public class auditypes
{
public List<auditype> auditype { get; set; }
}
public class auditype
{
public string code { get; set; }
public string description { get; set; }
}
I call it with this function :
public List<auditypes> Execute<auditypes>(RestRequest request) where auditypes : new()
{
var client = new RestClient();
client.BaseUrl = "https://www.myurl.com/auditypes";
var response = client.Execute<auditypes>(request);
return response.Data as List<auditypes>;
}
public List<auditypes> GetCall()
{
var request = new RestRequest();
request.RequestFormat = DataFormat.Xml;
request.RootElement = "auditype";
return Execute<auditypes>(request);
}
but it always return null, does anyone knows why is this happening?
The generic parameter passed to Execute<T> is the type that should be deserialized by the RestSharp library. That means that your response.Data property is already of type T, which in your case is auditypes. But when you return you try to cast it to a List<auditypes> where no such cast exists.
Also, there is no need for the type constraint, as your method is not generic as it accepts an explicit type.
Refactor your method:
public auditypes Execute<auditypes>(RestRequest request)
{
var client = new RestClient();
client.BaseUrl = "https://www.myurl.com/auditypes";
var response = client.Execute<auditypes>(request);
return response.Data;
}
Finally, it work for me :)
public auditypes Execute<auditypes>(RestRequest request) where auditypes : new()
{
var client = new RestClient();
client.BaseUrl = "https://www.myurl.com/auditypes";
var response = client.Execute<auditypes>(request).Data;
return response;
}
public auditypes GetCall()
{
var request = new RestRequest();
request.RequestFormat = DataFormat.Xml;
return Execute<auditypes>(request);
}