I am unable to remove the slash while requesting to the Post API in c#.By default slash is added in the value, is there is a way to remove the slash in the string.I am sending the string array to api.I have used replace also but it is not working.
"[\"9782163865630.jpg\",\"9946239664158.jpg\",\"9946237403166.jpg\",\"10056487272478.jpg\",\"10056486322206.jpg\",\"10060074352670.jpg\",\"9999843459102.jpg\",\"9716071170078.jpg\",\"9716071497758.jpg\",\"10052987715614.jpg\",\"10052985683998.jpg\",\"10056390115358.jpg\",\"10056391622686.jpg\",\"10056391360542.jpg\",\"9837103120414.jpg\",\"9837102923806.jpg\",\"9837104857118.jpg\"]"
public void PostWebAPI(List<string> FileNameList)
{
string json = JsonConvert.SerializeObject(FileNameList).ToString();
json = json.Replace(#"\","");
var client = new RestClient("eg.api.stackflow.com/post");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AlwaysMultipartFormData = true;
request.AddParameter("filePaths", json);
request.AddParameter("bucketAsDir", "false");
IRestResponse response = client.Execute(request);
}
Visual Studio debugging:
The backslash \ is not a readable character in your string, its an escape character for the double quotes: \"; its telling the compiler that the " following the backslash is not a string delimiter but a regular character part of the string.
Consider you want to have a string that contains the following text: "Hello" (not Hello). You would write the following:
string s = "\"Hello\"";
s is really "Hello" but the debugger will show it as "\"Hello\"" because it has no better way to desambiguate to the user " as string delimiter from " as part of the string itself.
In short, the escape character \ inside a string tells the compiler that the following character is used in a way that is not the default interpretation the compiler would consider. Other expamples:
\": a regular double quote instead of the string delimiter "
\0: null charater instead of a regular 0
\n: new line character instead of a regular n
\t: tab character instead of a regular t
\\: backslash instead of the escape character \
etc.
Check here for the whole list.
So, to make a long story short, dont worry, your string really is: ["9782163865630.jpg","9946239664158.jpg","9946237403166.jpg",.... You can verify this by simply printing out the string to the console: Console.WriteLine(json);
The slash isn't actually in the string. You're trying to remove something that doesn't exist. The debugger is just escaping the double quotes. Click on the magnifier icon will get you some options on how the debugger displays it.
Each quotes " is a special symbol in C#.
Those backslashes \ just escape sequences for the quotes ".
It dont make your result error.
Try to write this in Visual Studio:
string myString = "This is my "string""; // Error
You can use a backslash before each quote (\") to fix it:
string myString = "This is my \"string\""; // This work well
Try this here
I was facing the problem with the above code using RestClient instead of it, I have used HttpClient, Now from API I am not getting the error. Slash is added to request paramater using RestClient but in HttpClient it is not added, due to this UnicodeEncoding.UTF8, "application/json" the actuall value is been passed in the parameter of the API.
public async Task CallAPIAsync(List<string> objFileNameList)
{
var Info = new APIModel
{
filePaths = objFileNameList,
bucketAsDir = "false"
};
string request = JsonConvert.SerializeObject(Info);
using (var client = new HttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var stringContent = new StringContent(request, UnicodeEncoding.UTF8, "application/json");
client.BaseAddress = new Uri("eg.api.stackflow.com/post");
var response = await client.PostAsync("post", stringContent);
var message = response.Content.ReadAsStringAsync().Result;
}
}
Related
I've tried everything but cannot seem to get a Variable into some text. I think the problem is that the test is in JSON format. I'm trying to pass a variable from a textbox in the UI to this variable, but for testing I've just created a local variable, as below. Here is my code:
Variable:
string Repo1 = "jamesbennett12345678990";
String I'm trying to add my variable into:
var UserAgent1 = new ProductInfoHeaderValue("ScraperBot", "1.0");
request.Headers.TryAddWithoutValidation("Authorization", "token testtesttesttest");
request.Headers.UserAgent.Add(UserAgent1);
//String here
request.Content = new StringContent("{\"name\":\"{Repo1}\"}");
I've read that to do this it is simply a case of putting curly braces around the variable but it doesnt work. I know this because the line - string Repo1 = "jamesbennett12345678990"; says that the variable is not in use.
This part is JSON Data that is getting passed using the HTPClient so I'm thinking as there are already Speachmarks escaped with backslashes that there might be a formatting problem here ---- ("{"name":"{Repo1"}")
I don't have any errors as such, only the one in VS saying the
var string Repo1 = "jamesbennett12345678990";
isn't actually in use.
I've also looked into string Interpolation.
try this
var json = System.Text.Json.JsonSerializer.Serialize(new {name=Repo1});
//or
var json = System.Text.Json.JsonSerializer.SerializeToElement(new {name=Repo1}).ToString();
//or
var json="{\"name\":\""+ Repo1+"\"}";
var content = new StringContent(json, Encoding.UTF8, "application/json");
I have this json data string below, which I need to do some cleaning before I can Deserialize into an object in C#. Here's my json string:
{'data':[
{'ID':'01','Name':'Name 1','Description':'abc','Skills':[{'Type':'abc','Technical':'abc','Description':'abc'}],'Status':false,'Inactive':0},
{'ID':'02','Name':'Name 2','Description':'abc','Skills':[{'Type':'abc','Technical':'abc','Description':'abc'}],'Status':false,'Inactive':0},
{'ID':'03','Name':'Name 3','Description':'abc','Skills':[{'Type':'abc','Technical':'abc','Description':'abc'}],'Status':false,'Inactive':1}]}
What I'm trying to do is REMOVE single quote (') character from the following field in the above data:
'Skills':[{'Type':'abc','Technical':'abc','Description':'abc'}]
So what I need to achieve is to have "Skills" field to look like this:
'Skills':[{Type:abc,Technical:abc,Description:abc}]
I designed this Regex patter:
(?<='Skills':\[\{)(.*?)(?=\}\],)
It matches the string below, but I don't know how to exclude single quotes.
'Type':'abc','Technical':'abc','Description':'abc'
Can someone please help?
It's better to modify the source to get pretty formatted JSON, it's not standard JSON format.
if you don't have access to modify the source output, you can use this :
string content = Console.ReadLine();
var matchResult = new Regex("(?<='Skills':).*?}]").Matches(content);
foreach(Match match in matchResult)
{
string matchValueWithoutSingleQuote = match.Value.Replace("'", string.Empty);
content = content.Replace(match.Value, matchValueWithoutSingleQuote);
}
Console.WriteLine(content);
Console.ReadLine();
the output is :
{'data':[
{'ID':'01','Name':'Name 1','Description':'abc','Skills':[{Type:abc,Technical:abc,Description:abc}],'Status':false,'Inactive':0},
{'ID':'02','Name':'Name 2','Description':'abc','Skills':[{Type:abc,Technical:abc,Description:abc}],'Status':false,'Inactive':0},
{'ID':'03','Name':'Name 3','Description':'abc','Skills':[{Type:abc,Technical:abc,Description:abc}],'Status':false,'Inactive':1}]}
Linq version :
string content = Console.ReadLine();
var matchResult = new Regex("(?<='Skills':).*?}]").Matches(content);
var jsonWithNormalizedSkillField = matchResult.Cast<Match>().Select(s => content.Replace(s.Value, s.Value.Replace("'", string.Empty))).FirstOrDefault();
Console.WriteLine(jsonWithNormalizedSkillField);
Console.ReadLine();
The Following string gives an error when using the following code:
data = await resposta.Content.ReadAsStringAsync();
dynamic j = JObject.Parse(data);
The data in contains the following string:
{"code": 100, "message": "The entity with the name "Esther Rea" its not in DB."}
How to take off the " from Esther Rea?
As suggested, the correct solution would be to have whoever's returning this value escape the quotes. However, if that's really not an option, you can try to brute-force your way into escaping the double quotes yourself, assuming the return schema is always the same, using something like this:
var pattern = "(\"message\":\\s+\")(?<messageContent>(.*))(\"})";
var regex = Regex.Match(data, pattern);
var message = regex.Groups["messageContent"].Value;
if (!string.IsNullOrEmpty(message))
{
message = message.Replace("\"", "\\\"");
var newData = Regex.Replace(data, pattern, "$1" + message + "$3");
var jObject = JObject.Parse(newData);
}
This will extract the actual message string and escapes all double quotes in it (message.Replace("\"", "\\\"");), causing serialization to succeed.
If you really want to remove the quotes instead of escaping them, you can do message = message.Replace("\"", "");
I have spotted something which seems off in the HttpWebRequest object.
If I run the following:
var q = "кот (";
(Note here 'кот' is written in Russian, apparently it means cat.)
var encoded = Uri.EscapeDataString(q);
var url = $"https://api.twitter.com/1.1/search/tweets.json?count=100&include_entities=true&q={encoded}";
I get the following value in url:
https://api.twitter.com/1.1/search/tweets.json?count=100&include_entities=true&q=%D0%BA%D0%BE%D1%82%20%28
If I then run this:
var r = (HttpWebRequest)WebRequest.Create(url);
r.GetResponse();
In Fiddler, the above is observed to actually make a request:
https://api.twitter.com/1.1/search/tweets.json?count=100&include_entities=true&q=%D0%BA%D0%BE%D1%82%20(
Note that the ( is not encoded as %28 as it was when I constructed the HttpWebRequest.
If instead I use:
q = "CAT ("
i.e. no Russian characters, only latin(?), I get this as the URL:
https://api.twitter.com/1.1/search/tweets.json?count=100&include_entities=true&q=CAT%20%28
And this is also the request observed in Fiddler.
To summarise, it seems when mixing latin and non latin characters, the ( is not being sent encoded.
Does anybody have any suggestions how to solve this?
UPDATE:
This is important because as far as I can tell it is the reason I can't successfully make these API queries to Twitter as it appears to be breaking our OAuth1 signing, we are getting:
HTTP/1.1 401 Authorization Required
{"errors":[{"code":32,"message":"Could not authenticate you."}]}
I can even edit the failing request in Fiddler and replace the ( with a %28 in the GET request, and it then succeeds on replaying it with this single change.
This may help... it appears that the behaviour of the Uri class is as follows:
var q = "кот (";
var encoded = Uri.EscapeDataString(q);
// encoded = %D0%BA%D0%BE%D1%82%20%28
var uri = new Uri("https://api.twitter.com/1.1/search/tweets.json?count=100&include_entities=true&q=" + encoded);
// uri.AbsoluteUri = https://api.twitter.com/1.1/search/tweets.json?count=100&include_entities=true&q=%D0%BA%D0%BE%D1%82%20(
var uri2 = new Uri("https://api.twitter.com/1.1/search/tweets.json?count=100&include_entities=true&q=CAT (");
// uri2.AbsoluteUri = https://api.twitter.com/1.1/search/tweets.json?count=100&include_entities=true&q=CAT%20(
var uri3 = new Uri("https://api.twitter.com/1.1/search/tweets.json?count=100&include_entities=true&q=кот (");
// uri3.AbsoluteUri = https://api.twitter.com/1.1/search/tweets.json?count=100&include_entities=true&q=%D0%BA%D0%BE%D1%82%20(
I cannot debug into the .NET Framework code at the moment, but I suspect use of Uri.EscapeDataString might be incorrect WRT non-Latin chars and brackets?
Does the request with the unencoded bracket actually work? If so I would suggest the bracket does not need encoding...
UPDATE: I actually think this might be a bug in Uri?
I have a question that I feel will be simple to answer: I have the code
function ApplicantNameMatchedInitialPayment() {
var applicantName = '<%= ViewData["ApplicantName"] %>';
var fullName = applicantName.split(' ');
if (fullName.length == 2)
{
var firstName = fullName[0].toLowerCase();
var lastName = fullName[1].toLowerCase();
var nameOnCard = $("#name-on-card").val().toLowerCase();
if(nameOnCard.includes(firstName) & (nameOnCard.includes(lastName)))
{
return true;
}
}
return false;
}
I am trying to handle a case where my user enters their name with an apostrophe. When the ViewData Object is filled during live execution, the customer's name will show up in the 'applicantName' variable. The problem is that if I enter a name like "De'Leon", a JS error is thrown in the console because of an incorrect escape sequence.. and the string will not be read correctly. I want to take any string that is passed in from my C# Viewdata object and handle the apostrophes dynamically so that no errors are thrown and so that my javascript understands that everything should just be one string. A little help with the string formatting and escape character?
If you want to just escape apostrophes in JavaScript you could try to simply replace them with \’:
s = s.replace("'", "\'");
It won’t affect your further work with this string so if you write it to the console it will output a result without backslash:
var s = "De'Leon";
s = s.replace("'", "\'");
console.log(s); // > De'Leon
If you're using .NET version 4 or later, you can use HttpUtility.JavaScriptStringEncode.