Receive API Response in c# - c#

im trying to get a this value that i send with JSON string POST, when i receive the response in postman, there's value like status, id, etc that i not POST, while i do understand get the value from JSON string,
i dont quite understand to get a receive API value like status and Name
what i do tried recently
public class Condition
{
public string status { get; set; }
public string name { get; set; }
public string positition { get; set; }
public int no_id { get; set; }
public string time_auth { get; set; }
public string account_type { get; set; }
}
for the method
public partial class ResponseJSON
{
public bool Result(string jsonData, string URL, out string status)
{
bool resultresponse = false;
var request = (HttpWebRequest)WebRequest.Create(URL);
request.ContentType = "application/json";
request.Method = "POST";
var writer = new StreamWriter(request.GetRequestStream());
string wrote = jsonData;
writer.Write(wrote);
var httpResponse = (HttpWebResponse)request.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
var result = streamReader.ReadToEnd();
dynamic R = JsonConvert.DeserializeObject<dynamic>(wrote);
status = R.auth_type;
return resultresponse;
}
}
and for the main
string jsonData = #"{
'auth_type':'7',
'staff_id':'1234567890',
'staff_pin': '1234'}";
dynamic data = JObject.Parse(jsonData);
string URL = "Link URL";
string status = string.Empty;
ResponseJSON responseJSON = new ResponseJSON();
responseJSON.Result(jsonData, URL, out status);

You might want to declare the same class "Condition" on your client side, so you can deserialize the response with Newtonsoft with something like this:
var conditionResponse = JsonConvert.DeserializeObject<Condition>(jsonData);

Related

How to pass incoming integer parameter value in json request while making a POST request

Making a POST request for the API, passing incoming json body as hardcoded string. Fine with all hardcoded values, only need to pass ID based on incoming parameter incomingID (int)
Checked couple of articles/questions, but didn't any clear answer. Please suggest/guide how to replace this hardcoded value 123456 with incoming parameter value (incomingID)
Replace field in Json file with some other value
How to replace placeholders inside json string?
private void CallAPI(int incomingID)
{
const string apiURL = "API URL"; // some test API
string getInfoResult = string.Empty;
try
{
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(apiURL);
webrequest.Method = "POST";
webrequest.ContentType = "application/json";
using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
{
string json = "{\"Information\":{\"messageHeader\":{\"message\":\"getInfo\",\"transactionDate\":\"2021-05-11T12:05:54.000\", \"transactionID\":\"2021-05-15T12:05:54.000-12345\",\"payLoadFormat\":\"V1\",\"ID\":123456}}}"; //pass this incomingID based on parameter value
streamWriter.Write(json);
}
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
getInfoResult = responseStream.ReadToEnd();
webresponse.Close();
}
catch (Exception ex)
{
throw ex;
}
}
To make this, you can use simple interpolation:
string json = $"{{\"Information\":{{\"messageHeader\":{{\"message\":\"getInfo\",\"transactionDate\":\"2021-05-11T12:05:54.000\", \"transactionID\":\"2021-05-15T12:05:54.000-12345\",\"payLoadFormat\":\"V1\",\"ID\":{incomingID}}}}}}}"
Note that open and close brackets should be repeated twice to escape them. But, this is weird and not so common way to make JSON strings. Better use serialization to achieve your goal. For an example, use Newtonsoft.Json nuget to (de)serialize your objects. What you need to do:
Create your models as separate classes:
PayloadFormat.cs
[Newtonsoft.Json.JsonConverter(typeof(StringEnumConverter))] // this string will force your enum serialize as "V1" instead of "0"
public enum PayloadFormat
{
V1,
V2,
V3
}
MessageHeader.cs
public class MessageHeader
{
public MessageHeader(string message, DateTime transactionDate, string transactionId, PayloadFormat payloadFormat, int id)
{
Message = message;
TransactionDate = transactionDate;
TransactionId = transactionId;
PayloadFormat = payloadFormat;
Id = id;
}
public string Message { get; set; }
public DateTime TransactionDate { get; set; } // change type if you need to
public string TransactionId { get; set; } // change type if you need to
public PayloadFormat PayloadFormat { get; set; } // change type if you need to
public int Id { get; set; }
}
Information.cs
public class Information
{
public Information(MessageHeader messageHeader)
{
MessageHeader = messageHeader;
}
public MessageHeader MessageHeader { get; set; }
}
Create an instance of your Information class:
var information = new Information(new MessageHeader("getInfo", DateTime.Now, $"{DateTime.Now}-12345", PayloadFormat.V1, incomingID));
Serialize your string (make sure you are using Newtonsoft.Json;):
var json = JsonConvert.SerializeObject(information);
Then use your json as you need to. The result will be:
{
"MessageHeader": {
"Message": "getInfo",
"TransactionDate": "2022-05-17T19:45:33.2161326+05:00",
"TransactionId": "17.05.2022 19:45:33-12345",
"PayloadFormat": "V1",
"Id": 5
}
}

RestSharp doesn't get data or content of response

I have a route in my web service that receives POST request with Json body and returns simple array in Json format. I'm using PostMan for testing route and it works perfectly. but when I'm using RestSharp it doesn't get any content (or data in deserialization case).
Here is my C# code :
public static async Task<string> UpdateProfile(Profile user, string serviceUrl)
{
string bodyraw = JsonConvert.SerializeObject(user)
var client = new RestClient(serviceUrl);
var request = new RestRequest();
request.Method = Method.POST;
request.Parameters.Clear();
request.AddParameter("application/json", bodyraw, ParameterType.RequestBody);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = await client.ExecuteTaskAsync<Profile>(request);
return response.Data.Address;
}
And here is the Profile Class:
public class Profile
{
public string Name { get; set; }
public string Family { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Address { get; set; }
public string Postal_code { get; set; }
public string Education { get; set; }
public string Gender { get; set; }
public string Age { get; set; }
public string Default_contact { get; set; }
public override string ToString()
{
return string.Concat(Name," " ,Family, " ", Address);
}
}
And this is PostMan OutPut:
{
"Name": "Holma",
"Family": "Kool",
"Email": "dr#gmail.com",
"Mobile": "09063094744",
"Address": "some city- basic av. sq 60",
"Postal_code": "10246666",
"Education": "1",
"Gender": "male",
"Age": "35"
}
And the PHP code that I used is:
function silverum_update_user_profile($request ){
$parameters = $request->get_json_params();// this is a WordPress method and works just fine
$name=sanitize_text_field($parameters['name']);
$family=sanitize_text_field($parameters['family']);
$email=sanitize_text_field($parameters['email']);
$mobile=sanitize_text_field($parameters['mobile']);
$address=sanitize_text_field($parameters['address']);
$postal_code=sanitize_text_field($parameters['postal_code']);
$education=sanitize_text_field($parameters['education']);
$gender=sanitize_text_field($parameters['gender']);
$age=sanitize_text_field($parameters['age']);
$extdp = [
"Name"=>$name,
"Family"=>$family,
"Email"=>$email,
"Mobile"=>$mobile,
"Address"=>$address,
"Postal_code"=>$postal_code,
"Education"=>$education,
"Gender"=>$gender,
"Age"=>$age
];
return $extdp;
}
When PHP method returns "Parameter" its OK and both PostMan and RestSharp can see output content but when method Returns new Array only PostMan is able to recive returnd object. I spent a couple of hour on the issue but didn't get anywhere. help please.
Try using the AddJsonBody() method within the RestRequest object as opposed to adding the parameter manually.
public static async Task<string> UpdateProfile(Profile user, string serviceUrl)
{
var client = new RestClient(serviceUrl);
var request = new RestRequest();
request.Method = Method.POST;
request.AddJsonBody(user);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = await client.ExecuteAsync<Profile>(request);
return response.Data.Address;
}

Parsing uniquely named nested JSON

Preface: I know of JSON.NET but I cannot use it (client machine).
I need to parse the JSON returned by http://api.fixer.io/latest?base=USD into 3 columns, date, currencyCode, and rate. The issue is with the nested "rates" portion. The currency code is the name of the first element which means I can't use "key" and "value" properties. The only way I know of is to hardcode each possible currency code, which is what I have currently in the code below. I want to be able to use key/value pairs to pull the code/rate simultaneously.
The JSON:
{"base":"USD",
"date":"2016-07-12",
"rates": {
"AUD":1.3101,
"BGN":1.7633,
"BRL":3.2829,
"CAD":1.3029,
etc....}
}
My code so far:
static void Main(string[] args)
{
var curDate = "2001-01-01";
var URL = #"http://api.fixer.io/" + curDate + "?base=USD";
Console.WriteLine(URL);
//WebRequest wrGetURL = WebRequest.Create(URL);
var text = "";
//wrGetURL.ContentType = "application/json; charset=utf-8";
HttpWebRequest httpWebRequest = System.Net.WebRequest.Create(URL) as HttpWebRequest;
using (HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse)
{
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
throw new Exception(string.Format("Server error (HTTP {0}: {1}).",
httpWebResponse.StatusCode, httpWebResponse.StatusDescription));
}
Stream stream = httpWebResponse.GetResponseStream();
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(JSONRead));
JSONRead objResponse = (JSONRead)dataContractJsonSerializer.ReadObject(stream);
Console.WriteLine(objResponse.rates.AUD);
}
Console.ReadLine();
}
[DataContract]
public class JSONRead
{
[DataMember(Name = "date")]
public string date { get; set; }
[DataMember(Name = "rates")]
public Rates rates { get; set; }
[DataMember(Name = "base")]
public string bases { get; set; }
}
[DataContract]
public class Rates
{
[DataMember(Name = "AUD")]
public string AUD { get; set; }
//[DataMember(Name = "key")]
//public string key { get; set; }
//[DataMember(Name = "value")]
//public string value { get; set; }
}
What I am trying to return:
Date Code Rate
2016-07-12 AUD 1.3101
2016-07-12 GBN 1.7633
etc...
I had to use the DataContractJsonSerializerSettings and set UseSimpleDictionaryFormat to true. It then reads the nested object into a Dictionary object properly. Thanks for the help #Plutonix.

How to get UserContactLists from constant contact using c#

I am going to use Constant contact for email marketing. I am not getting how to get userContactList which are all there in my constant contact account.If anyone have any idea please help me.
Thanks in advance
Here is some code I wrote a while ago that returns the user list ID based on the name of an existing user list. its all C# and uses RESTSharp library which you can install inside your VS project using Nuget.
public static string GetContactListIDByListName(string listname)
{
feedData = string.Empty;
id = string.Empty;
name = string.Empty;
status = string.Empty;
modified_date = string.Empty;
created_date = string.Empty;
contact_count = 0;
Stream stream = null;
StreamReader streamReader = null;
var client = new RestClient(ccURL);
var request = new RestRequest("/v2/lists?modified_since=[DATE]&api_key=[API-KEY]", Method.GET);
request.AddHeader("Authorization", "Bearer [ACCESS-TOKEN]");
request.AddHeader("X-Originating-Ip", "[SERVER-IP]");
request.AddHeader("Accept", "application/json");
IRestResponse response = client.Execute(request);
feedData = response.Content;
// DESERIALIZE Mashery JSON Response
byte[] byteArray = Encoding.ASCII.GetBytes(feedData);
MemoryStream myStream = new MemoryStream(byteArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Mashery.GetAllListsDef[]));
object result = serializer.ReadObject(myStream);
Mashery.GetAllListsDef[] jsonObj = result as Mashery.GetAllListsDef[];
foreach (Mashery.GetAllListsDef myResult in jsonObj)
{
if (myResult.name.ToUpper().Equals(listname.ToUpper()))
{
return myResult.id.ToString();
}
}
return "";
}
// JSON Definition For [GET All Lists] End Point Method
[Serializable, XmlRoot("GetAllListsDef"), DataContract(Name = "GetAllListsDef")]
public class GetAllListsDef
{
[XmlElement("id"), DataMember(Name = "id")]
public string id { get; set; }
[XmlElement("name"), DataMember(Name = "name")]
public string name { get; set; }
[XmlElement("status"), DataMember(Name = "status")]
public string status { get; set; }
[XmlElement("created_date"), DataMember(Name = "created_date")]
public string created_date { get; set; }
[XmlElement("modified_date"), DataMember(Name = "modified_date")]
public string modified_date { get; set; }
[XmlElement("contact_count"), DataMember(Name = "contact_count")]
public string contact_count { get; set; }
}

Calling WebApi with complex object parameter using WebClient

I need to call a WebApi using WebClient where have to pass an object as parameter. I have my WebApi method as similar to bellow code:
example URI: localhost:8080/Api/DocRepoApi/PostDoc
[HttpPost]
public string PostDoc (DocRepoViewModel docRepo)
{
return string.enpty;
}
and then DocRepoViewModel is:
public class DocRepoViewModel
{
public string Roles { get; set; }
public string CategoryName { get; set; }
public List<AttachmentViewModel> AttachmentInfo { get; set; }
}
AttachmentViewModel is:
public class AttachmentViewModel
{
public string AttachmentName { get; set; }
public byte[] AttachmentBytes { get; set; }
public string AttachmentType { get; set; }
}
New I need to call PostDoc method from my MVC controller (not javascript ajax). How can I pass this specific parameter that I can make the call and get all data in my WebApi method. Can we do it by WebClient? Or there are better way. Please help.
You could use the PostAsJsonAsync method as follows:
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("localhost:8080/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var docViewModel = new DocRepoViewModel() { CategoryName = "Foo", Roles= "role1,role2" };
var attachmentInfo = new List<AttachmentViewModel>() { AttachmentName = "Bar", AttachmentType = "Baz", AttachmentBytes = File.ReadAllBytes("c:\test.txt" };
docViewModel.AttachmentInfo = attachmentInfo;
response = await client.PostAsJsonAsync("DocRepoApi/PostDoc", docViewModel);
if (response.IsSuccessStatusCode)
{
// do stuff
}
}
}
Asp .net reference
Check out following code.
string url = "Your Url";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.KeepAlive = false;
request.ContentType = "application/json";
request.Method = "POST";
var entity = new Entity(); //your custom object.
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(entity));
request.ContentLength = bytes.Length;
Stream data = request.GetRequestStream();
data.Write(bytes, 0, bytes.Length);
data.Close();
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string message = reader.ReadToEnd();
var responseReuslt = JsonConvert.Deserialize<YourDataContract>(message);
}
}

Categories

Resources