本文介绍了逃脱UTF-8 JSON重音字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  {X:艺术120  - Incapacità迪intendere的Ø迪VOLERE } 

我需要改变这一点,我想我已经来改变编码的东西,但我不知道是什么:

  {X:艺术120  -  Incapacit\\\à intendere的迪迪ØVOLERE } 

代码:

 字符串标签=120艺术 - Incapacitàintendere的迪迪ØVOLERE 
JObject J =新JObject();
j.Add(新JProperty(×,标记));
字符串s = j.ToString();
编码编码=新的UTF8Encoding(假);
字符串文件名= @C:\temp\test.json使用(的FileStream oFileStream =新的FileStream(文件名,FileMode.OpenOrCreate,FileAccess.Write))
{
使用(StreamWriter的oStreamWriter =新的StreamWriter(oFileStream,编码))
{

oStreamWriter.Write(j.ToString());
oStreamWriter.Flush();
oStreamWriter.Close();
}
oFileStream.Close();
}


解决方案

与其他人一样说,你要使用StringEscapeHandling.EscapeNonAscii

 使用系统; 
:使用System.IO;
使用Newtonsoft.Json;
使用Newtonsoft.Json.Linq;

公共类节目
{
公共静态无效的主要()
{
字符串标签=艺术120 - Incapacità迪intendere的Ø迪VOLERE ;
JObject J =新JObject();
j.Add(新JProperty(×,标记));
字符串s = j.ToString();

变种SR =新的StringWriter();
变种jsonWriter =新JsonTextWriter(SR){
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};
新JsonSerializer()序列化(jsonWriter,J)。

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



输出



  {X:艺术120  -  Incapacit\\\à intendere的迪迪ØVOLERE} 


the code below produce this output:

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

i need to change to this, i suppose i've to change something on encoding but i don't know what:

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

code:

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();
}
解决方案

Like others said, you want to use 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());
    }
}

outputs

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

https://dotnetfiddle.net/s5VppR

这篇关于逃脱UTF-8 JSON重音字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 06:04