I have build a JSON string (to be posted to a web service), and I used the C# StringBuilder class to do this. The problem is, that when I insert quotes, the StringBuilder class escapes them.
I am currently building the JSON string as such:
StringBuilder dataJSON= new StringBuilder();
dataJSON.Append("{");
dataJSON.Append(" " + Convert.ToChar(34) + "data" + Convert.ToChar(34) + ": {");
dataJSON.Append(" " + Convert.ToChar(34) + "urls" + Convert.ToChar(34) + ": [");
dataJSON.Append(" {" + Convert.ToChar(34) + "url" + Convert.ToChar(34) + ": " + Convert.ToChar(34) + domain + "/" + path[0] + Convert.ToChar(34) + "}");
dataJSON.Append(" ,{" + Convert.ToChar(34) + "url" + Convert.ToChar(34) + ": " + Convert.ToChar(34) + domain + "/" + path[1] + Convert.ToChar(34) + "}");
dataJSON.Append(" ]");
dataJSON.Append(" }");
dataJSON.Append("}");
However, the command:
dataJSON.ToString(); results in the string:
{ \"data\": { \"urls\": [ {\"url\": \"domain/test1.html\"} , {\"url\": \"domain/test2.html\"} ] }}
Notice the escaped quotes? This is really screwing me up, because the server can't handle the slashes.
My desired (which posts fine to my server when I use PHP) should be:
{ "data": { "urls": [ {"url": "domain/test1.html"} , {"url": "domain/test2.html"} ] }}
Is there ANY way to get a string in C# to include quotes that will result in the desired string?
Many thanks!
Brett
The QuickWatch/Watch window will add the extra \ in. If you view it in the Text Visualizer, you will not see them:
QuickWatch:
"{ \"data\": { \"urls\": [ {\"url\": \"domain/path1\"} ,{\"url\":
\"domain/path2\"} ] }}"
Visualizer (the actual output):
{ "data": { "urls": [ {"url": "domain/path1"} ,{"url": "domain/path2"} ] }}
The \ indicates that the quotes have been escaped and will be included in the final string as you're expecting them to be. I.e. there's nothing wrong with your output.
NB. I used "\"" instead of Convert.ToChar(34) when I tested this.
You may have more luck using the Newtonsoft.JSON library, or alternately just escaping the slashes yourself as \" in your string literals instead of using Char(34).
dataJSON.Append(" \"data\": {");
Related
Okay so I have some c# that generated href anchor tags styled as list items and throws it onto an aspx page like so;
html += "<a href='../InspectionView.aspx' class='list-group-item' id=''>Inspection ID: " + inspectionID + " - Due Date: " + inspDueDate + " - Inspector(s): Bob Williams <span style='min-width:75px' class='label label-primary pull-right'>" + status + "</span></a>";
Now this is in a loop, the variables are pulled from a SQL database and used to populate that html string.
Now, what I'm trying to do is have it so when the user clicks on one of the generated hrefs, and is redirected to the next page, the variable inspectionID is passed forward. I thought there might be someway of storing it in the ID of the href tag but I dont know where to go from there.
Thanks a lot.
Add a query string parameter.
html += "<a href='../InspectionView.aspx?inspectionID='" + inspectionID + " class='list-group-item' id=''>Inspection ID: " + inspectionID + " - Due Date: " + inspDueDate + " - Inspector(s): Bob Williams <span style='min-width:75px' class='label label-primary pull-right'>" + status + "</span></a>";
For reading on the receiving page:
string inspectionID = Request.QueryString["inspectionID"];
See
https://msdn.microsoft.com/en-us/library/system.web.httprequest.querystring(v=vs.110).aspx
a very simple way is to stick into a query string. Since this isn't a server control it might be the only way to it.
something like...
html += "<a href='../InspectionView.aspx?InspectionID="+HttpUtility.UrlEncode(Inspection_ID.ToString())+"&anyotherQSField="+HttpUtility.UrlEncode(anyotherQSFieldVariable) + "' class='list-group-item'> - Due Date: " + inspDueDate + " - Inspector(s): Bob Williams <span style='min-width:75px' class='label label-primary pull-right'>" + status + "</span></a>";
Then in InspectionView.aspx,get values with something like:
String strInspection_ID = Request.QueryString["InspectionID"];
You likely need to convert to string for this to work for the ID.
You dont have to use HttpUtility.UrlEncode for Inspection_ID but if you have other strings you want to use in QS that might contain spaces or other odd characters - it would be wise.
So I need to convert this string into an object essentially.
{
"character_list": [
{
"character_id": "5428018587875812257",
"name": {
"first": "gixtr2",
"first_lower": "gixtr2"
},
"faction_id": "3",
"head_id": "1",
"title_id": "17",
"times": {
"creation": "1355333636",
"creation_date": "2012-12-12 17:33:56.0",
"last_save": "1385855627",
"last_save_date": "2013-11-30 23:53:47.0",
"last_login": "1385850955",
"last_login_date": "2013-11-30 22:35:55.0",
"login_count": "334",
"minutes_played": "16492"
},
"certs": {
"earned_points": "13219",
"gifted_points": "384",
"spent_points": "12538",
"available_points": "1065",
"percent_to_next": "0.05122222222318"
},
"battle_rank": {
"percent_to_next": "4",
"value": "50"
},
"profile_id": "14",
"daily_ribbon": {
"count": "5",
"time": "1385787600",
"date": "2013-11-30 05:00:00.0"
}
}
],
"returned": 1
}
I get that character_list is an array but there are other objects INSIDE that array. I would like help parsing those objects into the main object.
Code
It's rather lengthy so it's in a text file. I'm doing this in c#.NET.
You're not that far off the mark. The main problem is that character_list is an array in your JSON, but the character_list property in your JsonHttp class does not represent an array or a list, so it won't deserialize properly.
Here's what you need to do:
First rename your character_list class to Character. This class represents the stats for a single character in your game, does it not?
In your JsonHttp class, change the type of your character_list property from character_list to List<Character>.
In your Character class, either rename your daily_ribbons property to daily_ribbon (singular), or mark it with [JsonProperty("daily_ribbon")]. The property name in the JSON is singular, so it needs to match your class somehow.
With those changes, you should be able to deserialize your JSON and extract the data as shown below (where json is your JSON string as posted in your question):
JsonHttp obj = JsonConvert.DeserializeObject<JsonHttp>(json);
foreach (Character c in obj.character_list)
{
Console.WriteLine("Character id: " + c.character_id);
Console.WriteLine("Name: " + c.name.first);
Console.WriteLine("Faction id: " + c.faction_id);
Console.WriteLine("Head id: " + c.head_id);
Console.WriteLine("Title id: " + c.title_id);
Console.WriteLine("Profile id: " + c.profile_id);
Console.WriteLine("Creation date: " + c.times.creation_date);
Console.WriteLine("Last login date: " + c.times.last_login_date);
Console.WriteLine("Last save date: " + c.times.last_save_date);
Console.WriteLine("Login count: " + c.times.login_count);
Console.WriteLine("Minutes played: " + c.times.minutes_played);
Console.WriteLine("Earned points: " + c.certs.earned_points);
Console.WriteLine("Gifted points: " + c.certs.gifted_points);
Console.WriteLine("Spent points: " + c.certs.spent_points);
Console.WriteLine("Available points: " + c.certs.available_points);
Console.WriteLine("Percent to next cert: " + c.certs.percent_to_next);
Console.WriteLine("Battle rank value: " + c.battle_rank.value);
Console.WriteLine("Percent to next rank: " + c.battle_rank.percent_to_next);
Console.WriteLine("Daily ribbon count: " + c.daily_ribbons.count);
Console.WriteLine("Daily ribbon date: " + c.daily_ribbons.date);
}
Here is a Fiddle with the full working code: https://dotnetfiddle.net/Zt6aWd
I Have a messagebox to display some text and data (if existing) within database. The current Issue is trying to show nulls and trying to convert to ShortDate. I've taken two approach but none quite work in the way I need.
The first approach uses Ternary concatenation within the string but it behaves really weird.
DialogResult DuplicateMessage = MessageBox.Show("A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
+ "\n Existing Client: " + DuplicateName.Forename + " " + DuplicateName.Surname
+ "\n Date of Birth: " + DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ",
,"Possible Duplicate Client", MessageBoxButtons.YesNo);
Currently The message box only shows the line breaks and the Date Of birth. Not even the text "Date of Birth"
If I remove Tertiary and conversion and simply have
DialogResult DuplicateMessage = MessageBox.Show("A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
+ "\n Existing Client: " + DuplicateName.Forename + " " + DuplicateName.Surname
+ "\n Date of Birth: " + DuplicateName.DOB
,"Possible Duplicate Client", MessageBoxButtons.YesNo);
This works, shows everything. Only issue is that the Date of birth is in the wrong format. Was wondering how do I make it so the date is in short date format and will show everything.
all Properties Of 'DuplicateName' are nullable,
I suspect this is a problem with operator precedence using the conditional operator. It's likely including string concatenations as part of the condition being tested, rather than as part of the result. You can explicitly enclose the elements of that operator with parentheses to identify which strings belong therein and which do not:
"\n Date of Birth: " + (DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ")
Additionally, if DOB is a DateTime? then you can simplify your code a little:
"\n Date of Birth: " + (DuplicateName.DOB.HasValue ? DuplicateName.DOB.Value.ToString("yyyy-mm-dd") : " ")
There's no need to use Convert on Nullable<T> types, you can more easily (and safely) make use of the HasValue and Value properties.
You can fix it by using another pair of parentheses:
(DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB))
In your first case, you're concatenating a huge string together (because you don't use any parentheses) and then testing that for null. It's equivalent to this:
var stringToTest = "A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
+ "\n Existing Client: " + DuplicateName.Forename + " " + DuplicateName.Surname
+ "\n Date of Birth: " + DuplicateName.DOB;
DialogResult DuplicateMessage =
MessageBox.Show(stringToTest != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ",
,"Possible Duplicate Client", MessageBoxButtons.YesNo);
This question already has answers here:
How to display the text in MVC?
(4 answers)
Closed 8 years ago.
I want to show a output in textbox in MVC. But its not displaying anything. I used the following code and i attached screenshot below:
#Html.TextAreaFor(up => up.CompileOutput)
foreach (CompilerError CompErr in results.Errors)
{
userProgram.CompileOutput = "Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
return View(userProgram);
The first image shows that the output is binded with that particular textbox. But in browser (image 2) shows nothing in the textbox (red colour)
I am even wondering why you did not got an exception. return view(string) will look for a view with the string parameter as name, it will not show the text.
I would suggest you use ViewBag instead. So you set your error text in a property you name as follow:
foreach (CompilerError CompErr in results.Errors)
{
userProgram.CompileOutput = "Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
ViewBag.ErrorText = userProgram.CompileOutput;
You can later on retrieve the value by simply calling ViewBag.ErrorText from you Razor view
Why not try doing it another way?
#Html.TextArea("CompileOutput", userProgram.CompileOutput)
Hey guys I am trying to print a list of responses from an API into labels and one issue I have is that the response (from JSON) is a string with a shortened link in it. When I put that string into a label the link is not recognized as a link the browser just think it is HTML so there is no underline or pointer. How can I solve this? I have already tried to HtmlEncode it and that did not help.
Here is what I am trying to do.
lblResponse.InnerHtml += "<strong>created_at:</strong> " + item.created_at
+ "<strong>  text:</strong> " + HttpUtility.HtmlEncode(item.text) + "<br />";
Which returns this into the label. Though in my browser the shortened link is not recognized as a link. Advice?
created_at: Tue Apr 16 20:30:32 +0000 2013 text: Here is some social media news for the week... http://t.co/RR5DKvqUjd
Thanks in advance for the help.
var date = "Tue Apr 16 20:30:32 +0000 2013";
var text = "Here is some social media news for the week... http://t.co/RR5DKvqUjd";
var textwithanchor = Regex.Replace(text, #"\(?\bhttp://[-A-Za-z0-9+&##/%?=~_()|!:,.;]*[-A-Za-z0-9+&##/%=~_()|]", delegate(Match match)
{
return string.Format("<a href='{0}'>{0}</a>", match.ToString());
});
var html = "<strong>created_at:</strong> " + date + "<strong>  text:</strong> " + textwithanchor + "<br />";
Regex gracefully borrowed from here: http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html but please take note of the caveats.
Try something like this:
lblResponse.InnerHtml += "<strong>created_at:</strong> " +
item.created_at +
"<strong>  text:</strong> " +
"<a href=\"" + item.text + "\"" +
HttpUtility.HtmlEncode(item.text) +
"</a><br />";