Are there any classes/functions available to be used for easy JSON escaping? I'd rather not have to write my own.
I use System.Web.HttpUtility.JavaScriptStringEncode
string quoted = HttpUtility.JavaScriptStringEncode(input);
For those using the very popular Json.Net project from Newtonsoft the task is trivial:
using Newtonsoft.Json;
....
var s = JsonConvert.ToString(#"a\b");
Console.WriteLine(s);
....
This code prints:
"a\\b"
That is, the resulting string value contains the quotes as well as the escaped backslash.
Building on the answer by Dejan, what you can do is import System.Web.Helpers .NET Framework assembly, then use the following function:
static string EscapeForJson(string s) {
string quoted = System.Web.Helpers.Json.Encode(s);
return quoted.Substring(1, quoted.Length - 2);
}
The Substring call is required, since Encode automatically surrounds strings with double quotes.
Yep, just add the following function to your Utils class or something:
public static string cleanForJSON(string s)
{
if (s == null || s.Length == 0) {
return "";
}
char c = '\0';
int i;
int len = s.Length;
StringBuilder sb = new StringBuilder(len + 4);
String t;
for (i = 0; i < len; i += 1) {
c = s[i];
switch (c) {
case '\\':
case '"':
sb.Append('\\');
sb.Append(c);
break;
case '/':
sb.Append('\\');
sb.Append(c);
break;
case '\b':
sb.Append("\\b");
break;
case '\t':
sb.Append("\\t");
break;
case '\n':
sb.Append("\\n");
break;
case '\f':
sb.Append("\\f");
break;
case '\r':
sb.Append("\\r");
break;
default:
if (c < ' ') {
t = "000" + String.Format("X", c);
sb.Append("\\u" + t.Substring(t.Length - 4));
} else {
sb.Append(c);
}
break;
}
}
return sb.ToString();
}
I have used following code to escape the string value for json.
You need to add your '"' to the output of the following code:
public static string EscapeStringValue(string value)
{
const char BACK_SLASH = '\\';
const char SLASH = '/';
const char DBL_QUOTE = '"';
var output = new StringBuilder(value.Length);
foreach (char c in value)
{
switch (c)
{
case SLASH:
output.AppendFormat("{0}{1}", BACK_SLASH, SLASH);
break;
case BACK_SLASH:
output.AppendFormat("{0}{0}", BACK_SLASH);
break;
case DBL_QUOTE:
output.AppendFormat("{0}{1}",BACK_SLASH,DBL_QUOTE);
break;
default:
output.Append(c);
break;
}
}
return output.ToString();
}
In .Net Core 3+ and .Net 5+:
string escapedJsonString = JsonEncodedText.Encode(jsonString);
The methods offered here are faulty.
Why venture that far when you could just use System.Web.HttpUtility.JavaScriptEncode ?
If you're on a lower framework, you can just copy paste it from mono
Courtesy of the mono-project #
https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs
public static string JavaScriptStringEncode(string value, bool addDoubleQuotes)
{
if (string.IsNullOrEmpty(value))
return addDoubleQuotes ? "\"\"" : string.Empty;
int len = value.Length;
bool needEncode = false;
char c;
for (int i = 0; i < len; i++)
{
c = value[i];
if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
{
needEncode = true;
break;
}
}
if (!needEncode)
return addDoubleQuotes ? "\"" + value + "\"" : value;
var sb = new System.Text.StringBuilder();
if (addDoubleQuotes)
sb.Append('"');
for (int i = 0; i < len; i++)
{
c = value[i];
if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
sb.AppendFormat("\\u{0:x4}", (int)c);
else switch ((int)c)
{
case 8:
sb.Append("\\b");
break;
case 9:
sb.Append("\\t");
break;
case 10:
sb.Append("\\n");
break;
case 12:
sb.Append("\\f");
break;
case 13:
sb.Append("\\r");
break;
case 34:
sb.Append("\\\"");
break;
case 92:
sb.Append("\\\\");
break;
default:
sb.Append(c);
break;
}
}
if (addDoubleQuotes)
sb.Append('"');
return sb.ToString();
}
This can be compacted into
// https://github.com/mono/mono/blob/master/mcs/class/System.Json/System.Json/JsonValue.cs
public class SimpleJSON
{
private static bool NeedEscape(string src, int i)
{
char c = src[i];
return c < 32 || c == '"' || c == '\\'
// Broken lead surrogate
|| (c >= '\uD800' && c <= '\uDBFF' &&
(i == src.Length - 1 || src[i + 1] < '\uDC00' || src[i + 1] > '\uDFFF'))
// Broken tail surrogate
|| (c >= '\uDC00' && c <= '\uDFFF' &&
(i == 0 || src[i - 1] < '\uD800' || src[i - 1] > '\uDBFF'))
// To produce valid JavaScript
|| c == '\u2028' || c == '\u2029'
// Escape "</" for <script> tags
|| (c == '/' && i > 0 && src[i - 1] == '<');
}
public static string EscapeString(string src)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
int start = 0;
for (int i = 0; i < src.Length; i++)
if (NeedEscape(src, i))
{
sb.Append(src, start, i - start);
switch (src[i])
{
case '\b': sb.Append("\\b"); break;
case '\f': sb.Append("\\f"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
case '\"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '/': sb.Append("\\/"); break;
default:
sb.Append("\\u");
sb.Append(((int)src[i]).ToString("x04"));
break;
}
start = i + 1;
}
sb.Append(src, start, src.Length - start);
return sb.ToString();
}
}
I ran speed tests on some of these answers for a long string and a short string. Clive Paterson's code won by a good bit, presumably because the others are taking into account serialization options. Here are my results:
Apple Banana
System.Web.HttpUtility.JavaScriptStringEncode: 140ms
System.Web.Helpers.Json.Encode: 326ms
Newtonsoft.Json.JsonConvert.ToString: 230ms
Clive Paterson: 108ms
\\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\"things\to\escape\some\long\path\with\lots"\of\things\to\escape
System.Web.HttpUtility.JavaScriptStringEncode: 2849ms
System.Web.Helpers.Json.Encode: 3300ms
Newtonsoft.Json.JsonConvert.ToString: 2827ms
Clive Paterson: 1173ms
And here is the test code:
public static void Main(string[] args)
{
var testStr1 = "Apple Banana";
var testStr2 = #"\\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\""things\to\escape\some\long\path\with\lots""\of\things\to\escape";
foreach (var testStr in new[] { testStr1, testStr2 })
{
var results = new Dictionary<string,List<long>>();
for (var n = 0; n < 10; n++)
{
var count = 1000 * 1000;
var sw = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var s = System.Web.HttpUtility.JavaScriptStringEncode(testStr);
}
var t = sw.ElapsedMilliseconds;
results.GetOrCreate("System.Web.HttpUtility.JavaScriptStringEncode").Add(t);
sw = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var s = System.Web.Helpers.Json.Encode(testStr);
}
t = sw.ElapsedMilliseconds;
results.GetOrCreate("System.Web.Helpers.Json.Encode").Add(t);
sw = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var s = Newtonsoft.Json.JsonConvert.ToString(testStr);
}
t = sw.ElapsedMilliseconds;
results.GetOrCreate("Newtonsoft.Json.JsonConvert.ToString").Add(t);
sw = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var s = cleanForJSON(testStr);
}
t = sw.ElapsedMilliseconds;
results.GetOrCreate("Clive Paterson").Add(t);
}
Console.WriteLine(testStr);
foreach (var result in results)
{
Console.WriteLine(result.Key + ": " + Math.Round(result.Value.Skip(1).Average()) + "ms");
}
Console.WriteLine();
}
Console.ReadLine();
}
I would also recommend using the JSON.NET library mentioned, but if you have to escape unicode characters (e.g. \uXXXX format) in the resulting JSON string, you may have to do it yourself. Take a look at Converting Unicode strings to escaped ascii string for an example.
I nice one-liner, used JsonConvert as others have but added substring to remove the added quotes and backslash.
var escapedJsonString = JsonConvert.ToString(JsonString).Substring(1, JsonString.Length - 2);
What about System.Web.Helpers.Json.Encode(...) (see http://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode(v=vs.111).aspx)?
String.Format("X", c);
That just outputs: X
Try this instead:
string t = ((int)c).ToString("X");
sb.Append("\\u" + t.PadLeft(4, '0'));
There's a Json library at Codeplex
I chose to use System.Web.Script.Serialization.JavaScriptSerializer.
I have a small static helper class defined as follows:
internal static partial class Serialization
{
static JavaScriptSerializer serializer;
static Serialization()
{
serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
}
public static string ToJSON<T>(T obj)
{
return serializer.Serialize(obj);
}
public static T FromJSON<T>(string data)
{
if (Common.IsEmpty(data))
return default(T);
else
return serializer.Deserialize<T>(data);
}
}
To serialize anything I just call Serialization.ToJSON(itemToSerialize)
To deserialize I just call Serialization.FromJSON<T>(jsonValueOfTypeT)
Well this questions is probably gonna be closed before I get an answer... I am trying to program a very simple calculator and this works flawlessly:
private void button1_Click(object sender, EventArgs e)
{
string[] input = rtbInput.Text.Split(' ');
rtbInput.Text += " = " + CalculateNumber(input).ToString();
}
long CalculateNumber(string[] input)
{
long curValue = 0;
curValue = long.Parse(input[0]);
//LOOK FOR PARENTHASIS, LAST INDEX, SEARCH FROM THERE UNTIL FIRST INDEX, RUN THIS AGAIN FOR THAT.
//THEN REPLACE "5 + (3 + 3)" with 5 + 6. So calculate 3 + 3 = 6 and replace ( until ) with answer.
if (rtbInput.Text.Contains("(") && rtbInput.Text.Contains(")"))
{
int c = 0;
int startNum;
int len;
string s = "No";
}
int i = 0;
while (i < (input.Length - 1))
{
switch (input[i])
{
case "+":
curValue += long.Parse(input[i + 1]);
break;
case "-":
curValue -= long.Parse(input[i + 1]);
break;
case "*":
curValue = curValue * long.Parse(input[i + 1]);
break;
case "/":
curValue = curValue / long.Parse(input[i + 1]);
break;
}
i++;
}
return curValue;
}
this works superbly. But when trying to add capability to calculate Parenthasis "(3 * 3) = 9" and i implement this code:
long CalculateNumber(string[] input)
{
long curValue = 0;
curValue = long.Parse(input[0]);
//LOOK FOR PARENTHASIS, LAST INDEX, SEARCH FROM THERE UNTIL FIRST INDEX, RUN THIS AGAIN FOR THAT.
//THEN REPLACE "5 + (3 + 3)" with 5 + 6. So calculate 3 + 3 = 6 and replace ( until ) with answer.
if (rtbInput.Text.Contains("(") && rtbInput.Text.Contains(")"))
{
int c = 0;
int startNum;
int len;
string s = "No";
//while there are still parenthasis in the input, do this
if (c < rtbInput.Text.Split('(').Count() - 1) //REPLACE WITH WHILE
{
startNum = rtbInput.Text.LastIndexOf('(') + 1;
len = rtbInput.Text.IndexOf(')', startNum);// - startNum;
s = rtbInput.Text.Substring(startNum, len);
this.Name = s;
//NOW REPLACE THIS WITH THE RETURN OF CalculateParenthasis.Split(' ')
rtbInput.Text = rtbInput.Text.Replace("(" + s + ")", CalculateParenthasis(s.Split(' ')).ToString());
}
long CalculateParenthasis(string[] input)
{
long curValue = 0;
curValue = long.Parse(input[0]);
button1.Text += curValue.ToString();
int i = 0;
while (i < (input.Length - 1))
{
switch (input[i])
{
case "+":
curValue += long.Parse(input[i + 1]);
break;
case "-":
curValue -= long.Parse(input[i + 1]);
break;
case "*":
curValue = curValue * long.Parse(input[i + 1]);
break;
case "/":
curValue = curValue / long.Parse(input[i + 1]);
break;
}
i++;
}
return curValue;
}
As you can see the CalculateParenthasis() function works exactly the same as CalculateNumber() but takes the number between the parenthasis, but this errors at the switch statement saying the input string was the wrong format? WTH? I barely don't know how to even ask this question, seems like something tiny and easy being wrong but I just can't see it.
Based on my test, I reproduced the problem you meet.
However, I find it is very hard for us to complete it because of its complexity.
Therefore, I recommend that you use Reverse Poland algorithm to make the calculator.
I make a code example to make it and you can refer to it.
Code:
public class Example
{
public static Stack<string> operStack = new Stack<string>();
public static Stack<string> numStack = new Stack<string>();
static bool IsNumber(string s)
{
return Regex.IsMatch(s, #"\d+");
}
static bool IsSiZe(string s)
{
string ts = "+-*/";
return ts.IndexOf(s) > -1;
}
static int Level(string s)
{
int i = 0;
switch (s)
{
case ",":
i = 0;
break;
case "(":
case ")":
case "#":
i = 1;
break;
case "+":
case "-":
i = 2;
break;
case "*":
case "/":
i = 3;
break;
}
return i;
}
public static void Calc(Stack<string> numStack, Stack<string> operStack)
{
int rightnum = int.Parse(numStack.Pop());
int leftnum = int.Parse(numStack.Pop());
string oper = operStack.Pop();
switch (oper)
{
case "+":
numStack.Push((leftnum + rightnum).ToString());
break;
case "-":
numStack.Push((leftnum - rightnum).ToString());
break;
case "*":
numStack.Push((leftnum * rightnum).ToString());
break;
case "/":
numStack.Push((leftnum / rightnum).ToString());
break;
}
}
public static void ToNiBoLan(string exp)
{
operStack.Push("#"); //Push into the stack for comparsion
string token = "";
for (int i = 0; i < exp.Length; i++)
{
if (IsNumber(exp[i].ToString())) //If it is number
{
token += exp[i].ToString();
}
else if (exp[i].ToString() == "(")
{
operStack.Push(exp[i].ToString());
if (IsNumber(token))
numStack.Push(token);
token = "";
}
else if (IsSiZe(exp[i].ToString()))
{
if (IsNumber(token))
numStack.Push(token);
token = "";
int item = Level(exp[i].ToString()).CompareTo(Level(operStack.Peek())); //Comparison operator precedence
if (item > 0) //If the priority is higher than the top of the stack, the operator is pushed onto the stack
{
operStack.Push(exp[i].ToString());
}
else //If the operator is less than or equal to the top of the stack, calculate and push the operator onto the stack
{
Calc(numStack, operStack);
operStack.Push(exp[i].ToString());
}
}
else if (exp[i].ToString() == ")")
{
if (IsNumber(token))
numStack.Push(token);
token = "";
while (operStack.Peek() != "(")
{
Calc(numStack, operStack);
}
token = numStack.Pop(); //Take out the numbers for the next calculation
operStack.Pop(); //Eligible left parenthesis popped
}
else //End of traversal
{
if (IsNumber(token))
numStack.Push(token);
token = "";
while (numStack.Count > 1)
{
Calc(numStack, operStack);
}
}
}
}
}
Use it in winforms:
private void button1_Click(object sender, EventArgs e)
{
//For comparison, add "#" at the end of the expression
string text = richTextBox1.Text.Trim() + "#";
Example.ToNiBoLan(text);
richTextBox1.Text = Example.numStack.Pop().ToString();
}
Besides, you can refer to the link Reverse polish notation C# don't work correctly.
I really don't know how to phrase my title, help me out.
I am having an issue with a game I am making. The game's objective is to eat an apple that appears on the map for points. When you eat it, another apple appears in a random location inside the little box.
As you see the apple goes out of the bounds. But it doesn't always happen on the first time I get to it. Also, there is a # at the very far right for some reason.
Here is the code:
The drawing happens in the Draw() method, so you should look at that first.
using System;
public class MainClass
{
public const int WIDTH = 20, HEIGHT = 20;
public static int Points, X, Y, FruitX, FruitY;
public static bool GameOver = false;
public static string Direction;
public static Random Rand = new Random();
public static void Start()
{
Console.Clear();
GameOver = false;
Direction = "Stop";
X = WIDTH/2;
Y = HEIGHT/2;
FruitX = Rand.Next(100)%WIDTH/2;
FruitY = Rand.Next(100)%HEIGHT/2;
}
public static void Draw()
{
Console.Clear();
for (int i = 0; i < WIDTH; i++)
{
Console.Write("# ");
}
for (int i = 0; i < HEIGHT - 1; i++)
{
for (int j = 0; j < WIDTH; j++)
{
Console.Write(j == 0 ? "# " : " ");
if (j == WIDTH - 1)
{
Console.Write("# ");
}
if (i == Y && j == X)
{
Console.Write("O");
}
else if (i == FruitY && j == FruitX)
{
Console.Write("🍎");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
for (int i = 0; i < WIDTH + 1; i++)
{
Console.Write("# ");
}
Console.WriteLine($"\nPoints: {Points}");
}
public static void InputHandler()
{
ConsoleKeyInfo UserInput = Console.ReadKey();
switch (UserInput.KeyChar)
{
case 'w':
Direction = "Up";
break;
case 'a':
Direction = "Left";
break;
case 's':
Direction = "Down";
break;
case 'd':
Direction = "Right";
break;
case 'x':
GameOver = true;
break;
default:
break;
}
}
public static void GameHandler()
{
switch (Direction)
{
case "Up":
Y--;
break;
case "Down":
Y++;
break;
case "Left":
X--;
break;
case "Right":
X++;
break;
default:
break;
}
GameOver = X > WIDTH || X < 0 || Y < 0 || Y > HEIGHT;
if (X == FruitX && Y == FruitY)
{
Points += 10;
FruitX = Rand.Next(100)%WIDTH/2;
FruitY = Rand.Next(100)%HEIGHT/2;
}
}
public static void Main(string[] args)
{
Start();
while (!GameOver)
{
Draw();
InputHandler();
GameHandler();
}
Console.Clear();
}
}
the program should ask for a number and print all the primes numbers between 1 to the number the user entered... why isn't it working?
bool isPrime = true;
int primes = 0;
Console.WriteLine("Enter a number");
int N = int.Parse(Console.ReadLine());
for (int i = 2; i <= N; i++)
{
for (int j = 2; j <= Math.Sqrt(i); j++)
{
if (i % j == 0)
{
isPrime = false;
}
}
if (isPrime)
{
Console.WriteLine(i + " is a prime number");
primes++;
}
}
Console.WriteLine("Between 1 to " + N + " there are " + primes + " prime numbers");
You have put the boolean out of the loops. So, once it is false, it will never be true in other loops and this cause the issue.
int primes = 0;
Console.WriteLine("Enter a number");
int N = int.Parse(Console.ReadLine());
for (int i = 2; i <= N; i++)
{
bool isPrime = true;
for (int j = 2; j <= Math.Sqrt(i); j++)
{
if (i % j == 0)
{
isPrime = false;
}
}
if (isPrime)
{
Console.WriteLine(i + " is a prime number");
primes++;
}
}
Console.WriteLine("Between 1 to " + N + " there are " + primes + " prime numbers");
First define this class:
public static class PrimeHelper
{
public static bool IsPrime(int candidate)
{
if ((candidate & 1) == 0)
{
if (candidate == 2)
{
return true;
}
else
{
return false;
}
}
for (int i = 3; (i * i) <= candidate; i += 2)
{
if ((candidate % i) == 0)
{
return false;
}
}
return candidate != 1;
}
}
then call it in your application:
var finalNumber = int.Parse(Console.ReadLine());
for (int i = 0; i < finalNumber; i++)
{
bool prime = PrimeHelper.IsPrime(i);
if (prime)
{
Console.Write("Prime: ");
Console.WriteLine(i);
}
}
using System;
namespace gpa
{
class gpa
{
static void Main(string [] args)
{
double credit = 0;
double totalCreditHours = 0;
char grade = ' ';
double gradePoints = 0;
double totalGradePoints = 0;
int counter = 0;
double gpa = 0;
do
{
Console.Write("Enter letter grade for class #{0} \n(use A, B, C, or D. Type 0 after all classes entered.): ", counter += 1);
char userInput = char.Parse(Console.ReadLine());
if (userInput == '0')
{
break;
}
else
{
grade = userInput;
Console.Write("Enter your credit hours: ");
credit = int.Parse(Console.ReadLine());
switch (grade)
{
case 'A': gradePoints = 4;
break;
case 'B': gradePoints = 3;
break;
case 'C': gradePoints = 2;
break;
case 'D': gradePoints = 1;
break;
}
totalGradePoints = totalGradePoints + (credit * gradePoints);
totalCreditHours = totalCreditHours + credit;
}
} while (grade != 0);
gpa = CalculateGPA(totalGradePoints, totalCreditHours);
Console.Write("Your GPA is ", gpa);
Console.ReadKey();
}
static double CalculateGPA(double totalGradePoints, double totalCreditHours)
{
return (totalGradePoints / totalCreditHours);
}
}
}
----this last part is what i think is wrong, but i am not sure how to fix it. It will not output the actual calculated gpa
You need this line instead -
Console.Write("Your GPA is " + gpa);
Or
Console.Write("Your GPA is {0}" ,gpa);