gpt4 book ai didi

c# - 在 utf-8 json 上转义重音字符

转载 作者:太空狗 更新时间:2023-10-30 00:31:09 24 4
gpt4 key购买 nike

下面的代码产生这个输出:

{"x": "Art. 120 - Incapacità di intendere o di volere"}

我需要对此进行更改,我想我必须更改一些编码但我不知道是什么:

{"x": "Art. 120 - Incapacit\u00e0 di intendere o di volere"}

代码:

string label = "Art. 120 - Incapacità di intendere o di volere";
JObject j = new JObject();
j.Add(new JProperty("x", label));
string s = j.ToString();
Encoding encoding = new UTF8Encoding(false);
string filename = @"c:\temp\test.json";
using (FileStream oFileStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter oStreamWriter = new StreamWriter(oFileStream, encoding))
{
oStreamWriter.Write(j.ToString());
oStreamWriter.Flush();
oStreamWriter.Close();
}
oFileStream.Close();
}

最佳答案

正如其他人所说,您想使用 StringEscapeHandling.EscapeNonAscii

using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class Program
{
public static void Main()
{
string label = "Art. 120 - Incapacità di intendere o di volere";
JObject j = new JObject();
j.Add(new JProperty("x", label));
string s = j.ToString();

var sr = new StringWriter();
var jsonWriter = new JsonTextWriter(sr) {
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};
new JsonSerializer().Serialize(jsonWriter, j);

Console.Out.WriteLine(sr.ToString());
}
}

输出

{"x":"Art. 120 - Incapacit\u00e0 di intendere o di volere"}

https://dotnetfiddle.net/s5VppR

关于c# - 在 utf-8 json 上转义重音字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29899386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com