Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 419
Jamey McElveen Avatar asked Jun 20 '12 18:06

Jamey McElveen


2 Answers

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);
}
like image 193
CD Smith Avatar answered Sep 18 '22 12:09

CD Smith


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;
        }
like image 29
Regfor Avatar answered Sep 20 '22 12:09

Regfor