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("\"", "");
Related
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;
}
}
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();
Pretty sure we all do string.format and define some string in a specifed format.
I have a string which is always formatted in a way like this:
const string myString = string.Format("pt:{0}-first:{1}", inputString);
To get {0}, I can always check for pt:{ and read till }.
But what is the best/recommended way to extract {0} & {1} from the above variable myString ?
A Regex version of answer, but again, assuming your input doesnt contain '-'
var example = = "pt:hello-first:23";
var str = "pt:(?<First>[^-]+)-first:(?<Second>[^%]+)";
var match = new Regex(str).Match(example);
var first = match.Groups["First"].Value;
var second = match.Groups["Second"].Value;
It might be a good idea that you define what your variable can/cannot contain.
Not sure if this is the best way to do it, but it's the most obvious:
string example = "pt:123-first:456";
var split = example.Split('-');
var pt = split[0].Substring(split[0].IndexOf(':') + 1);
var first = split[1].Substring(split[1].IndexOf(':') + 1);
As Shawn said, if you can guarantee that the variables wont contain either : or - this will be adequate.
I am using "nslookup" to get machine name from IP.
nslookup 1.2.3.4
Output is multiline and machine name's length dynamic chars. How can I extract "DynamicLengthString" from all output. All suggestions IndexOf and Split, but when I try to do like that, I was not a good solution for me. Any advice ?
Server: volvo.toyota.opel.tata
Address: 5.6.7.8
Name: DynamicLengthString.toyota.opel.tata
Address: 1.2.3.4
I made it the goold old c# way without regex.
string input = #"Server: volvo.toyota.opel.tata
Address: 5.6.7.8
Name: DynamicLengtdfdfhString.toyota.opel.tata
Address: 1.2.3.4";
string targetLineStart = "Name:";
string[] allLines = input.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
string targetLine = String.Empty;
foreach (string line in allLines)
if (line.StartsWith(targetLineStart))
{
targetLine = line;
}
System.Console.WriteLine(targetLine);
string dynamicLengthString = targetLine.Remove(0, targetLineStart.Length).Split('.')[0].Trim();
System.Console.WriteLine("<<" + dynamicLengthString + ">>");
System.Console.ReadKey();
This extracts "DynamicLengtdfdfhString" from the given input, no matter where the Name-Line is and no matter what comes afterwards.
This is the console version to test & verify it.
You can use Regex
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string Content = "Server: volvo.toyota.opel.tata \rAddress: 5.6.7.8 \rName: DynamicLengthString.toyota.opel.tata \rAddress: 1.2.3.4";
string Pattern = "(?<=DynamicLengthString)(?s)(.*$)";
//string Pattern = #"/^Dy*$/";
MatchCollection matchList = Regex.Matches(Content, Pattern);
Console.WriteLine("Running");
foreach(Match match in matchList)
{
Console.WriteLine(match.Value);
}
}
}
I'm going to assume your output is exactly like you put it.
string output = ExactlyAsInTheQuestion();
var fourthLine = output.Split(Environment.NewLine)[3];
var nameValue = fourthLine.Substring(9); //skips over "Name: "
var firstPartBeforePeriod = nameValue.Split('.')[0];
//firstPartBeforePeriod should equal "DynamicLengthString"
Note that this is a barebones example:
Either check all array indexes before you access them, or be prepared to catch IndexOutOfRangeExceptions.
I've assumed that the four spaces between "Name:" and "DynamicLengthString" are four spaces. If they are a tab character, you'll need to adjust the Substring(9) method to Substring(6).
If "DynamicLengthString" is supposed to also have periods in its value, then my answer does not apply. You'll need to use a regex in that case.
Note: I'm aware that you dismissed Split:
All suggestions IndexOf and Split, but when I try to do like that, I was not a good solution for me.
But based on only this description, it's impossible to know if the issue was in getting Split to work, or it actually being unusable for your situation.
Trying to join a list of strings together using string.join. When I use the Separator string " OR " the white spaces are being replaced with "+" which is breaking my targetUri string. Below is the code used to join.
if (DocumentSearchListViewModel.Filter == null)
{
return "http://000.000.00.00:8080/value/value/search/json?terms=value%20OR%20value&target=TEST2&maxResults=5";
}
var targetUri = "http://000.000.00.00:8080/value/value/search/json?";
NameValueCollection termsString = System.Web.HttpUtility.ParseQueryString(string.Empty);
if (!string.IsNullOrWhiteSpace(DocumentSearchListViewModel.Filter.Keywords))
{
if (!string.IsNullOrWhiteSpace(DocumentSearchListViewModel.Filter.Author))
{
DocumentSearchListViewModel.Filter.Keywords += (" " + DocumentSearchListViewModel.Filter.Author);
}
IList<string> keywords = DocumentSearchListViewModel.Filter.Keywords.Split();
termsString["terms"] = string.Join(" OR ", keywords);
}
targetUri += termsString.ToString();
targetUri += "&target=TEST2&maxResults=";
targetUri += DocumentSearchListViewModel.Filter.MaxNumberOfResults ?? "5";
return targetUri;
I have done many searches on Google but haven't been able to find anything that talks about string.join replacing characters. And during my debugging I was able to narrow it down to on the termsString line as where the problem occurs.
Here is an actual example of the string I get out: terms=value1+OR+value2+OR+value3
How would I stop the white spaces from being replaced with + characters?
Cheers,
James
In order to get the URL decoded value on the server side, you should use:
var encoded = "terms=value1+OR+value2+OR+value3";
var decoded = System.Web.HttpUtility.UrlDecode(encoded);
#PanagiotisKanavos, regarding my previous suggestion of using %20 instead of space, take a look at this JS:
var uri1="terms=value1%20OR%20value2%20OR%20value3";
var uri2="terms=value1+OR+value+OR+value3";
document.write(decodeURIComponent(uri1));
document.write("<br/>");
document.write(decodeURIComponent(uri2));
If you run it, you'll see that encoding could be sensitive in some contexts.