我建议您使用Json.NET(它也是 ASP.NET MVC 4 的默认 JSON 序列化程序)及其JsonWriter
:
StringWriter errorsStringWriter = new StringWriter();
JsonWriter errorsJsonWriter = new JsonWriter(jsonStringWriter);
errorsJsonWriter.WriteStartObject();
errorsJsonWriter.WritePropertyName("fieldname");
errorsJsonWriter.WriteValue("some error for fieldname");
errorsJsonWriter.WritePropertyName("fieldname2");
errorsJsonWriter.WriteValue("some error for fieldname2");
...
errorsJsonWriter.WriteEndObject();
errorsJsonWriter.Flush();
您可以使用以下方式返回以这种方式生成的 JSON ContentResult
:
return Content(errorsStringWriter.GetStringBuilder().ToString(), "application/json");
更新
Json.NET还通过JObject
. 在这种情况下,您的代码可能如下所示:
var jsonObject = new JObject();
jsonObject.Add("fieldname", "some error for fieldname");
jsonObject.Add("fieldname2", "some error for fieldname2");
...
在这种情况下创建ContentResult
可能如下所示:
return Content(jsonObject.ToString(Newtonsoft.Json.Formatting.None), "application/json");