如何获得UTF-8 JSON
本文关键字:JSON UTF-8 何获得 | 更新日期: 2023-09-27 18:17:22
我正在使用LitJSON库,但事情变得有点奇怪。
你知道在转换时保留重音的JSON库吗?
下面是测试:
test.json
[{"id":"CS_001","name":"L'élément","type":"Tôt"},{"id":"CS_002","name":"L'outrage","type":"Tôt"},{"id":"CS_003","name":"Test","type":"Tôt"}]
test.cs
public class test : MonoBehaviour {
private string jsonString;
private JsonData cardData;
JsonData database;
void Start () {
jsonString = File.ReadAllText (Application.dataPath + "/test.json");
cardData = JsonMapper.ToObject (jsonString);
database = JsonMapper.ToJson (cardData);
Debug.Log (database.ToString ());
}
}
Debug.Log变成
[{"id":"CS_001","name":"L''u00E9l'u00E9ment","type":"T'u00F4t"},{"id":"CS_002","name":"L'outrage","type":"T'u00F4t"},{"id":"CS_003","name":"Test","type":"T'u00F4t"}]
任何想法如何得到一个适当的Json ?即使它与另一个JSON库。
内容类型:application/json;charset=utf-8指定内容为JSON格式,以utf-8字符编码进行编码。JSON的默认编码是UTF-8。在这种情况下,接收服务器显然不知道它正在处理UTF-8编码的JSON,您可能需要手动转换它:
byte[] encodedBytes = Encoding.UTF8.GetBytes(jsonString);
Encoding.Convert(Encoding.UTF8, Encoding.Unicode, encodedBytes);
或者尝试在请求中指定内容类型:
content-type: application/json; charset=utf-8
下面是一个使用Json的示例。Net对字符串进行反序列化:
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// Deserialize the JSON into a list of CardData
var ob = JsonConvert.DeserializeObject<List<CardData>>("[{'"id'":'"CS_001'",'"name'":'"L'élément'",'"type'":'"Tôt'"},{'"id'":'"CS_002'",'"name'":'"L'outrage'",'"type'":'"Tôt'"},{'"id'":'"CS_003'",'"name'":'"Test'",'"type'":'"Tôt'"}]" );
/*
The output will be:
id: CS_001, name: L'élément, type: Tôt
id: CS_002, name: L'outrage, type: Tôt
id: CS_003, name: Test, type: Tôt
*/
foreach(var i in ob){
Console.WriteLine(i);
}
}
}
// Class that will hold the deserialized data
// For demo puposes
public class CardData
{
public string id { get; set; }
public string name { get; set; }
public string type { get; set; }
public override string ToString(){
return String.Format("id: {0}, name: {1}, type: {2}",id, name, type);
}
}
现场演示
您可能使用错误的编码读取文本文件。尝试对File使用重载。ReadAllText,它接受Encoding参数并传递UTF8。