Converting PHP array of arrays to C# - c#

I am writing a C# client for a 3rd party API (I'm using the RestSharp nuget package). Their documentation contains PHP examples which I must translate to C#. Most of their samples are simple enough and I have been able to convert them to C# but I am struggling with one of them because it accepts an array of arrays. Here's the sample from their documentation:
$params = array (
'user_key' => 'X',
'client_id'=> 'X,
'label' => array(
array(
'language' => 'en_US',
'name' => 'English label',
),
array(
'language' => 'fr_CA',
'name' => 'French label',
),
),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.3rdparty.com/xxx/yyy');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apikey: YOURAPIKEY'));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
Here's what I have so far:
var labels = new Dictionary<string, string>()
{
{ "en_US", "English Label" },
{ "fr_CA", "French Label" }
};
var request = new RestRequest("/xxx/yyy", Method.POST) { RequestFormat = DataFormat.Json };
request.AddHeader("apikey", myApiKey);
request.AddParameter("user_key", myUserKey);
request.AddParameter("client_id", myClientId);
request.AddParameter("label", ???);
var client = new RestSharp.RestClient("https://api.3rdparty.com")
{
Timeout = timeout,
UserAgent = "My .NET REST Client"
};
var response = client.Execute(request);
Does anybody know how to convert the "labels" dictionary into a format that would be equivalent to PHP's http_build_query?

http_build_query($params) produces output that looks like this:
user_key=X&client_id=X&label%5B0%5D%5Blanguage%5D=en_US&label%5B0%5D%5Bname%5D=English+label&label%5B1%5D%5Blanguage%5D=fr_CA&label%5B1%5D%5Bname%5D=French+label
Which, decoded, looks like:
user_key=X&client_id=X&label[0][language]=en_US&label[0][name]=English label&label[1][language]=fr_CA&label[1][name]=French label
So, you should be able to do:
var request = new RestRequest("/xxx/yyy", Method.POST);
request.AddHeader("apikey", myApiKey);
request.AddParameter("user_key", myUserKey);
request.AddParameter("client_id", myClientId);
foreach (var item in labels.Select((pair, i) => new { index = i, language = pair.Key, name = pair.Value }))
{
request.AddParameter(string.Format("label[{0}][language]", item.index), item.language);
request.AddParameter(string.Format("label[{0}][name]", item.index), item.name);
}
Note that, from experimentation, I have noticed that RestSharp is encoding a space as %20 rather than as +. Hopefully not a problem.

You may use HttpBuildQuery that is the specular implementation of that PHP function.

Related

Unable to read params in site response url in C#

I am getting response like this from the Client :
http://192.168.25.241/CPMO.asmx?wsdl|context=
{transaction_id=9610842, ref_id=14943018526993,
service_id=CPA_MCOM_999, error_list=n/a, sub_eff_date=201705121715460,
notification_ind=2, error_code=1, destination_mobtel=0105660125,
keyword=dummy, CURRENT_STEP=0, sub_exp_date=201705131200000}
Note :
?wsdl|context=
{transaction_id=9610842, ref_id=14943018526993, service_id=CPA_MCOM_999, error_list=n/a, sub_eff_date=201705121715460, notification_ind=2, error_code=1, destination_mobtel=0105660125, keyword=dummy, CURRENT_STEP=0, sub_exp_date=201705131200000}
So How can I read this string within the {}, after reading the parameters, redirect to the particular URL (I mean above URL), Can anyone help me in C#?
You can read the string as explained below.
var text = "{transaction_id=9610842, ref_id=14943018526993, service_id=CPA_MCOM_999, error_list=n/a, sub_eff_date=201705121715460, notification_ind=2, error_code=1, destination_mobtel=0105660125, keyword=dummy, CURRENT_STEP=0, sub_exp_date=201705131200000}";
//replace {} from your string.
var dict = text.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(part => part.Split('='))
.ToDictionary(split => split[0], split => split[1]);

Error reading JSON from URL

I am trying to read json into my C# application from a url. When I run the application I keep getting a error:
"Additional Text encountered after finished reading JSON content: {. Path ",line 2, position 667".
This is from this URL
I checked the page and the view source and can't seem to find the problem. How do I fix this?
The JSON is derived from a php array that is json encoded and echoed:
$args = array( 'post_type' => 'product', 'posts_per_page' => 200, 'product_cat' => 'Alcopops' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo json_encode($product);
endwhile;
wp_reset_query();
That page doesn't contain valid json. Take a look at this:
"product_type":"simple"}{"id":246,"post":
there's no comma between } and {
Edit:
The problem is with your php, rather than the c#.
Try this:
$args = array( 'post_type' => 'product', 'posts_per_page' => 200, 'product_cat' => 'Alcopops' );
$loop = new WP_Query( $args );
echo json_encode($loop->get_posts());
wp_reset_query();
use WebClient :
var json = new WebClient().DownloadString("http://cbbnideas.com/brydens-website/products/?category=Alcopops");

Can't send information to REST Server

I'm using a REST Service library with C# called RestSharp. I've been trying for too long to send information to a emailforge(newsletter service) server but i couldn't make it so far. I can post, put and get basic information, but i can't do the same with fields or lists within the Json sent.
RestClient client = new RestClient();
client.BaseUrl = "https://s3s.fr/api/rest/1/";
client.Authenticator = new HttpBasicAuthenticator(splioUser, splioPass);
var request = new RestRequest("{item}", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddUrlSegment("item", "contact");
request.AddParameter("email", "test#test.com.br");
request.AddParameter("firstname", "Jhonny");
request.AddParameter("lastname", "Test");
request.AddParameter("lang", "EN");
And that's the result:
{"email":"test#test.com.br","date":"2013-12-20 18:43:42","firstname":"Jhonny","lastname":"Test","lang":"EN","fields":[{"id":"0","name":"sexo","value":""},{"id":"1","name":"nascimento","value":""},{"id":"2","name":"cidade","value":""},{"id":"3","name":"estado","value":""},{"id":"4","name":"data altera\u00e7\u00e3o do cadastro","value":""},{"id":"5","name":"data \u00faltima compra","value":""},{"id":"6","name":"data primeira compra","value":""},{"id":"7","name":"data de criacao do cadastro","value":""},{"id":"8","name":"data de ultimo login no site","value":""}],"lists":[]}
It seems that i can't include any values between "lists" and "fields" values.
There's a manual orienting how to do it using PHP:
$universe = 'testapi';
$pass = 'MySecretAPIKEY';
$resource = ‘contact‘ ;
$email = ‘old#s3s.fr’ $service_url = "https://$universe:$pass#s3s.fr/api/rest/1/$resource/$email";
$curl = curl_init($service_url);
$query = array ( 'email' => ‘newmail#s3s.fr', 'lang' => 'de', 'fields' => array ( array ( 'id' => '0', 'value' => 'bl10'), array ( 'name' => 'field2', 'value' => 'myothercustomfield_value'), ), 'lists' => array ( array ( 'name' => 'Test Api' ), array ( 'id' => '5', 'action' => 'unsubscribe' ), ), ) ;
$qstring = json_encode($query);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_POSTFIELDS,$qstring);
curl_setopt($curl,CURLOPT_HTTPHEADER,array("Expect:"));
$curl_response = curl_exec($curl);
curl_close($curl);
var_dump($curl_response);
var_dump(json_decode($curl_response, true));
Thanks in advance!
Using RestSharp, you should use the built in json serialization. See this previous answer for an example
ADDED
Also, I find that using Fiddler or a similar tool is very useful for debugging. Fiddler requires some configuration to monitor traffic for some use cases,

How to deserialize currencies list from openexchangerates.org to C# custom class or object?

I need to get currency values list in C# from here:
http://openexchangerates.org/currencies.json
which produces this kind of output:
{
"AED": "United Arab Emirates Dirham",
"AFN": "Afghan Afghani",
"ALL": "Albanian Lek",
"AMD": "Armenian Dram",
"ANG": "Netherlands Antillean Guilder",
"AOA": "Angolan Kwanza"
// and so on
}
I managed to get a string containing values above using C#, but I cannot find a way to deserialize that string into any custom class or anonymous object, so I am wondering how to do that?
Also, I am trying to use Json.NET to do that, but so far couldn't find a solution...
using Json.Net
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
--EDIT--
You can make it shorter
WebClient w = new WebClient();
string url = "http://openexchangerates.org/currencies.json";
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(w.DownloadString(url));
A solution using only .Net 4.0 and no third party libraries:
string url = "http://openexchangerates.org/currencies.json";
var client = new System.Net.WebClient();
string curStr = client.DownloadString(url);
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
var res = (js.DeserializeObject(curStr) as Dictionary<string, object>)
.Select(x => new { CurKey = x.Key, Currency = x.Value.ToString() });
Outputs a list of anonymous objects with the keys and values from the list as properties.
Enjoy :)

How to create JSON from C# dictionary similar to PHP

PHP code to make an array
$tag = array(
'tag_uid' => 1234,
'x' => 0,
'y' => 0
);
$tags[] = $tag;
OUTPUT: {"x":"0","y":"0","tag_uid":"1234"}
I want to make this as JSON array in C# with the same OUTPUT for that I need help, I can't figure out which array it will be? a simple array or what.
I have tag_uid which i can pass to function and i am using JSON.NET I don't know what should i need to write in the JsonArry function but I have tried to following
public JsonArray CreatePhotoTag(string userId)
{
Dictionary<string, object> tagParameters = new Dictionary<string, object>();
tagParameters.Add("x", "0");
tagParameters.Add("y", "0");
tagParameters.Add("tag_uid", userId);
JsonArray tagsarray = ???
return tagsarray ;
}
Please help me
I recommend switching to ServiceStack.NET Text. It is incredibly fast compared to JSON.NET.
You can serialize it like this:
ServiceStack.NET
var jsonSerializer = new JsonSerializer<Dictionary<String, Object>>();
var tagsArray = jsonSerializer.SerializeToString(tagParameters);
If you really want to use JSON.NET
JSON.NET
var tagsArray = JsonConvert.SerializeObject(tagParameters, Formatting.Indented);

Categories