How to get a UTF-8 JSON

被刻印的时光 ゝ 提交于 2019-12-04 13:55:53

Here's an example using Json.Net to deserialize the string:

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);   
    }
}

Live demo available here

Content-type: application/json; charset=utf-8 designates the content to be in JSON format, encoded in the UTF-8 character encoding. The default encoding for JSON is UTF-8. In this case the receiving server apparently does not know that it's dealing with JSON in the UTF-8 encoding and you may need to convert it manually:

byte[] encodedBytes = Encoding.UTF8.GetBytes(jsonString);
Encoding.Convert(Encoding.UTF8, Encoding.Unicode, encodedBytes);

or just try to specify the content type on your request:

content-type: application/json; charset=utf-8

It is possible that you read the text file using the wrong encoding. Try to use the overload for File.ReadAllText that takes in an Encoding argument and pass it UTF8.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!