What is the standard for text encoding for a JSON REST web api?

15,534

Solution 1

Something like this using the UTF-8 encoding, as a simplified example

public JsonResult Find(string term) 
{
    var items = service.Find(term);
    return Json(items,"application/json; charset=utf-8", JsonRequestBehavior.AllowGet);
}

Solution 2

Encode text using UTF-8, use JSON and HTTP encode. It's enough. HTTP encode is useful when you have line breaks and other special characters.

Standart is here http://www.ietf.org/rfc/rfc4627.txt?number=4627

But you should know that different json formatters could produce in special cases slightly different results, for example in questions how to encode date/time.

Example with UTF-8 and DataContractJsonSerializer:

        // Create a User object and serialize it to a JSON stream.
        public static string WriteFromObject()
        {
            //Create User object.
            User user = new User("Bob", 42);

            //Create a stream to serialize the object to.
            MemoryStream ms = new MemoryStream();

            // Serializer the User object to the stream.
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
            ser.WriteObject(ms, user);
            byte[] json = ms.ToArray();
            ms.Close();
            return Encoding.UTF8.GetString(json, 0, json.Length);

        }

        // Deserialize a JSON stream to a User object.
        public static User ReadToObject(string json)
        {
            User deserializedUser = new User();
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
            DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedUser.GetType());
            deserializedUser = ser.ReadObject(ms) as User;
            ms.Close();
            return deserializedUser;
        }
Share:
15,534
Jamey McElveen
Author by

Jamey McElveen

I am a Christian, I have three boys, Jake, Slater, Seth and a beautiful wife Connie. Application developer using primarily .NET/C#. I am using Objective-C for iPhone development. In the past I have also developed in Java, and Delphi.

Updated on June 20, 2022

Comments

  • Jamey McElveen
    Jamey McElveen almost 2 years

    I am building a Web API using MVC4 and some request return blocks of text that can have line brakes, special characters, Chinese and Spanish text. How should I escape/encode this information to be sent via the api?