在 C# 中解码 json 数据中的特殊字符
Decode special characters from json data in c#
我正在从 url 获取 json 格式的数据。一切正常,但有一个小问题是我得到的数据中有一些特殊字符,例如:
Get 50% off on Pizzas between 11am – 5pm.
–
这里的意思是'-',但是我怎样才能在c#中解码它,以便它把它当作'-'。
我试过使用 Html.decode 方法,它可以很好地处理 URL,但不能处理数据。
我不能把–
到处都换成'-'因为这不是个例,还有其他类似的字符。
我认为这是 question 的副本。
You can use HttpUtility.HtmlDecode
If you are using .NET 4.0+ you can also use WebUtility.HtmlDecode which does not require an extra assembly reference as it is available in the System.Net namespace.
工作正常:
https://dotnetfiddle.net/H9rpLe
using System;
public class Program
{
public static void Main()
{
string data = System.Net.WebUtility.HtmlDecode("Get 50% off on Pizzas between 11am – 5pm");
Console.WriteLine(data);
}
}
Output: Get 50% off on Pizzas between 11am – 5pm
尝试解码两次,因为您似乎已将其编码两次。第一次解码会将 –
转换为 –
,然后第二次解码会将其转换为 –
.
using System;
using System.Web;
public class Test
{
public static void Main()
{
string s = "Get 50% off on Pizzas between 11am – 5pm.";
Console.WriteLine(s);
string d = HttpUtility.HtmlDecode(s);
Console.WriteLine(d);
string e = HttpUtility.HtmlDecode(d);
Console.WriteLine(e);
}
}
我正在从 url 获取 json 格式的数据。一切正常,但有一个小问题是我得到的数据中有一些特殊字符,例如:
Get 50% off on Pizzas between 11am – 5pm.
–
这里的意思是'-',但是我怎样才能在c#中解码它,以便它把它当作'-'。
我试过使用 Html.decode 方法,它可以很好地处理 URL,但不能处理数据。
我不能把–
到处都换成'-'因为这不是个例,还有其他类似的字符。
我认为这是 question 的副本。
You can use HttpUtility.HtmlDecode
If you are using .NET 4.0+ you can also use WebUtility.HtmlDecode which does not require an extra assembly reference as it is available in the System.Net namespace.
工作正常:
https://dotnetfiddle.net/H9rpLe
using System;
public class Program
{
public static void Main()
{
string data = System.Net.WebUtility.HtmlDecode("Get 50% off on Pizzas between 11am – 5pm");
Console.WriteLine(data);
}
}
Output: Get 50% off on Pizzas between 11am – 5pm
尝试解码两次,因为您似乎已将其编码两次。第一次解码会将 –
转换为 –
,然后第二次解码会将其转换为 –
.
using System;
using System.Web;
public class Test
{
public static void Main()
{
string s = "Get 50% off on Pizzas between 11am – 5pm.";
Console.WriteLine(s);
string d = HttpUtility.HtmlDecode(s);
Console.WriteLine(d);
string e = HttpUtility.HtmlDecode(d);
Console.WriteLine(e);
}
}