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?
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);
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With