C# 替换 JSON 中的转义字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16692371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:40:47  来源:igfitidea点击:

Replacing escape characters from JSON

c#jsonstringreplace

提问by Cristiano Sarmento

I want to replace the "\" character from a JSON string by a empty space. How can I do that?

我想用空格替换 JSON 字符串中的“\”字符。我怎样才能做到这一点?

回答by Carlos Landeras

Just grab the json string and make it a String.Replace()

只需获取 json 字符串并使其成为 String.Replace()

string JsonContentFixed = JsonContentString.Replace(@"\", " ");

回答by vborutenko

try this

尝试这个

json.Replace(@"\", " ")

回答by Praveen

You can use Replace()

您可以使用替换()

string variable = "{\"data\": {\"id\": \"1\",\"name\": \"jon\"}}";
Console.WriteLine(variable.Replace("\", " "));

回答by Ionic? Biz?u

Basically you are asking how to replace the backslash in C#.

基本上你是在问如何替换 C# 中的反斜杠。

You have to use String.Replacemethod. The documentation tell us:

你必须使用String.Replace方法。文档告诉我们:

String.ReplaceMethod (String, String)

String.Replace方法(字符串,字符串)

Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

返回一个新字符串,其中当前实例中所有出现的指定字符串都替换为另一个指定字符串。

So, your string will take the value returned by Replacemethod:

因此,您的字符串将采用Replace方法返回的值:

jsonString= jsonString.Replace(@"\"," ");

回答by Anatoly Kostin

C# string assignment does that for you, although if name or value contains \ it will be double escaped. The proper way is to use variable.Replace("\\\\","\\"); or variable.Replace(@"\\",@"\"); This will remove double escaped \ character, Leaving REQUIRED \ in value. for example if JSON contains "Domain\Username" this will be returned as \"Domain\\\\Username\" assigning that to string will result you will have Domain\\Username

C# 字符串赋值为您完成了这项工作,但如果名称或值包含 \,它将被双重转义。正确的方法是使用 variable.Replace("\\\\","\\"); 或变量。替换(@"\\",@"\"); 这将删除双转义 \ 字符,在值中留下 REQUIRED \ 。例如,如果 JSON 包含“域\用户名”,这将作为“域\\\\用户名”返回,将其分配给字符串将导致您将拥有域\\用户名

回答by Brad

I have found that the easiest and best way to remove all escape characters from your JSON string, is to pass the string into Regex.Unescape()method. This method returns a new string with no ecapes, even \n \t etc, are removed.

我发现从 JSON 字符串中删除所有转义字符的最简单和最好的方法是将字符串传递给Regex.Unescape()方法。此方法返回一个没有转义符的新字符串,甚至删除了 \n \t 等。

See this MSDN article for more details: Regex.Unescape Method (String) (System.Text.RegularExpressions)

有关更多详细信息,请参阅此 MSDN 文章Regex.Unescape 方法(字符串)(System.Text.RegularExpressions)

回答by Alexei

Regex.Unescape()method will work just fine in most cases, but some particular cases require custom replacements. E.g. Regex.Unescape()will generate actual line breaks which are not supported in JSON.

Regex.Unescape()方法在大多数情况下都可以正常工作,但某些特殊情况需要自定义替换。例如,Regex.Unescape()将生成JSON 不支持的实际换行符。

Unescaped JSON:

未转义的 JSON:

{"comments_count":27,"comments":"<a name=\"comments\"><\/a>\n\n\t\n\t\n\t\t\n\t<div class=\"CommentsList\">\n\t\t<strong>COMENTARII<\/strong>\n\t\t"}

Regex.Unescape

正则表达式

{"comments_count":27,"comments":"<a name="comments"></a>

Replacements
    <div class="CommentsList">
        <strong>Comments</strong>
"}

Custom replacements

自定义替换

private string SanitizeReceivedJson(string uglyJson)
{
    var sb = new StringBuilder(uglyJson);
    sb.Replace("\\t", "\t");
    sb.Replace("\\n", "\n");
    sb.Replace("\\r", "\r");
    return sb.ToString();
}

{"comments_count":27,"comments":"<a name=\"comments\"><\/a>\n\n\t\n\t\n\t\t\n\t<div class=\"CommentsList\">\n\t\t<strong>COMENTARII<\/strong>"}

回答by Simba

If the json object is a string, in .Net the escape "\" characters are added, should you want to clean up the json string, JObject.Parse({string}) as demonstrated in the following code snippet cleans up nicely:

如果 json 对象是字符串,在 .Net 中会添加转义 "\" 字符,如果您想清理 json 字符串,JObject.Parse({string}) 如以下代码片段所示可以很好地清理:

var myJsonAsString = "{\"Name\": \"John\", \"LastName\": \"Doe\", \"Age\": 199 }";

var myCleanJsonObject = JObject.Parse(myJsonAsString);

Should give us a clean Json object with the escape characters removed.

应该给我们一个干净的 Json 对象,去掉转义字符。

{
"Name": "John",
"LastName": "Doe",
"Age": 199
}

回答by Johan Alzate

This type of escaped stringsare usually generated when you try to encode a string of JSON into JSON a second time. This causes something like "various levels of serialization"

这种类型的转义字符串通常在您尝试第二次将 JSON 字符串编码为 JSON 时生成。这会导致类似“不同级别的序列化”

Solution:

解决方案:

  • First, you need to deserialize the escaped string, but not to the target CLR type, but deserialize to another string
  • Repeat deserialization to string type again, if necessary.
  • Then perform final deserialization to the target type:
  • 首先需要将转义后的字符串反序列化,但不是反序列化到目标CLR类型,而是反序列化到另一个字符串
  • 如有必要,再次将反序列化为字符串类型。
  • 然后对目标类型执行最终反序列化:

Code:

代码:

// Initial example json string:  "\"{\\"Property1\\":1988,\\"Property2\\":\\"Some data :D\\"}\""    

// First, deserialize to another string (unescaped string).
string unescapedJsonString = JsonConvert.DeserializeObject<string>(escapedJsonString);
// Result: "{\"Property1\":1988,\"Property2\":\"Some data :D\"}"

// Second, deserialize to another string, again (in this case is necessary)
var finalUnescapedJsonString = JsonConvert.DeserializeObject<string>(unescapedJsonString);
// {"Property1":1988,"Property2":"Some data :D"}   This time prints a final, unescaped, json string:

// Finally, perform final deserialization to the target type, using the last unescaped string.
MyClass targetObject = JsonConvert.DeserializeObject<MyClass>(finalUnescapedJsonString);

回答by Ali Rasouli

In c# you have only one way to create standard JSON result:

在 c# 中,您只有一种创建标准 JSON 结果的方法:

You must be add one class with your custom property name and then return Json(myClassForJsonResult) as bottom code:

您必须使用自定义属性名称添加一个类,然后返回 Json(myClassForJsonResult) 作为底部代码:

public ActionResult testJsonData()
{
    var myClassForJsonResult=new YourClassOfYourCustomProperties();
    myClassForJsonResult.FirstPropertyStringType="first";
    myClassForJsonResult.SecondPropertyIntType=2;

    return Json(myClassForJsonResult);
}

class Defination:

类定义:

    public class YourClassOfYourCustomProperties
    {
        public string FirstPropertyStringType{ get; set; }
        public int SecondPropertyIntType{ get; set; }
    }