PHP中的json_encode方法,在5.4之前版本,中文会被unicode编码;5.4加入JSON_UNESCAPED_UNICODE,这个参数,设置不进行escape和unicode处理。
public class DefaultController : ApiController
{public IHttpActionResult GetProduct()
{
Product p =new Product{ Id = 1, Name = "中文"};
var msg = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new JsonContent(p)
};
var response = new ResponseMessageResult(msg);
return response;
}
private string ConvertUnicode(string test)
{
string result = "";
for (int i = 0; i < test.Length; i++)
{
int code = (int)test[i];
if (code > 32 && code < 127)
{
result += test[i];
}
else
result += string.Format("\\u{0:x4}", code);
}
return result;
}
}
public class JsonContent : HttpContent
{
private readonly MemoryStream _Stream = new MemoryStream();
public JsonContent(object value)
{
Headers.ContentType = new MediaTypeHeaderValue("application/json");
var jw = new JsonTextWriter(new StreamWriter(_Stream));
jw.Formatting = Formatting.Indented;
var serializer = new JsonSerializer();
serializer.NullValueHandling = NullValueHandling.Ignore;
serializer.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
serializer.Serialize(jw, value);
jw.Flush();
_Stream.Position = 0;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return _Stream.CopyToAsync(stream);
}
protected override bool TryComputeLength(out long length)
{
length = _Stream.Length;
return true;
}
}
public class Product
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public string Desc
{
get;
set;
}
}