Pass associative array to PHP API from C# - 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.

Related

C# http-get url JSON data and parse it to text..?

I don't really know how to ask this but basically,
I have a url http://URL.com/filename.json
and I would like to fetch the data from /filename.json and "convert it to text".
The url file contains the following: {"CurrentVersion": "1.0"}
and I would like to get the CurrentVersion and define a string with its value (1.0).
One possibility is to make use of System.Net.WebClient for downloading the data: (Outdated, see Edit below.)
// WebClient is outdated
string json;
using(var webClient = new WebClient())
{
json = webClient.DownloadString("http://URL.com/filename.json");
}
after downloading the string you can deserialize it with a framework like Json.Net. Because it is a simple JSON file we can deserialize it into a dictionary. This way we do not have to create an explicit class for it:
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
Now we can access the version like this:
var versionString = dict["CurrentVersion"];
Edit
Like #CodeCaster stated in the comments: The usage of System.Net.WebClient is outdated. Instead one should use System.Net.Http.HttpClient. Downloading the JSON could then look something like this:
// HttpClient is intended to be instantiated once per application, rather than per-use.
private readonly HttpClient _httpClient = new HttpClient();
[...]
var json = _httpClient.GetStringAsync("http://URL.com/filename.json");
// Do something with JSON

How to include Json string in uri c# 6

I have a c# object: a list with objects (objects have ID and Name)
Now I need to include the list of objects (it should be json string as far as I understand) in URL as parameter. How is it possible to do it?
If I understand you correctly, you need this.
var client = new WebClient();
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
string response = client.UploadString("http://mysite", "json string");

preparing Json Object for HttpClient Post method

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/

RestSharp - Serializing an # symbol

Using RestSharp 105.2.3
The API I am talking to requires use to send in a json body, but with a #c symbol as part of the field name. This is illegal in C# of course so I can't just use a dynamic object like below.
Is there a way to get the "#c" in the field name?
var client = new RestClient("https://aaa.bbb.com");
var request = new RestRequest(Method.POST);
request.AddJsonBody(new
{
#c=".Something",
username="johnsmith"
});
You could just use a string like this:
var client = new RestClient("https://aaa.bbb.com");
var request = new RestRequest(Method.POST);
string json = "{\"#c\":\".Something\", \"username\":\"johnsmith}";
request.AddJsonBody(json);

How to parse JSON using RestSharp?

var client = new RestClient("http://10.0.2.2:50670/api");
var request = new RestRequest("Inventory", Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
// execute the request to return a list of InventoryItem
RestResponse<JavaList<InventoryItem>> response = (RestResponse<JavaList<InventoryItem>>)client.Execute<JavaList<InventoryItem>>(request);
The content returned is a JSON string, an array of objects. The following is a short excerpt of it:
[{"Id":1,"Upc":"1234567890","Quantity":100,"Created":"2012-01-01T00:00:00","Category":"Tequila","TransactionType":"Audit","MetaData":"PATRON 750ML"},{"Id":2,"Upc":"2345678901","Quantity":110,"Created":"2012-01-01T00:00:00","Category":"Whiskey","TransactionType":"Audit","MetaData":"JACK DANIELS 750ML"},{"Id":3,"Upc":"3456789012","Quantity":150,"Created":"2012-01-01T00:00:00","Category":"Vodka","TransactionType":"Audit","MetaData":"ABSOLUT 750ml"}]
The error message:
Operation is not valid due to the current state of the object
What is wrong here? My InventoryItem has the same properties as each object in the JSON string. Am I missing a step?
I suspect that SimpleJson, used in RestSharp can't deserialise to a JavaList.
First I would try deserialising to a:
List<InventoryItem>
Failing that, I recommend ServiceStack.Text - .Net's fastest JSON library; and do:
var response = client.Execute(request);
var thingYouWant = JsonSerializer.DeserializeFromString<List<InventoryItem>>(response.Content);
This is actually what I do myself.
Edit (Thank you to commentators):
In newer versions this would now be:
var deserializer = new JsonDeserializer();
deserializer.Deserialize<List<InventoryItem>>(response);
Failing w/ auto-magic casting, I use this in a pinch:
var rc = new RestClient("https://api-ssl.bitly.com");
var rr = new RestRequest("/v3/link/clicks?access_token={access_token}&link={bitlyUrl}", Method.GET);
rr.AddUrlSegment("bitlyUrl", bitlyUrl);
rr.AddUrlSegment("access_token", BityAccessToken);
var response = rc.Execute(rr);
dynamic json = Newtonsoft.Json.Linq.JObject.Parse(response.Content);
var clicks = Convert.ToInt32(json.data.link_clicks.Value);

Categories