. Net MVC 4 Web Api output Json format, mvcjson
1. Add json output to Global
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));
1 protected void Application_Start () 2 {3 AreaRegistration. RegisterAllAreas (); 4 // Add the json Parsing Method http: // xxx/api/action? Json = true 5 GlobalConfiguration. configuration. formatters. jsonFormatter. mediaTypeMappings. add (new QueryStringMapping ("json", "true", "application/json"); 6 WebApiConfig. register (GlobalConfiguration. configuration); 7 FilterConfig. registerGlobalFilters (GlobalFilters. filters); 8 RouteConfig. registerRoutes (RouteTable. routes); 9 BundleConfig. registerBundles (BundleTable. bundles); 10}
2. Delete xml parsing in Global
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
1 protected void Application_Start () 2 {3 AreaRegistration. registerAllAreas (); 4 WebApiConfig. register (GlobalConfiguration. configuration); 5 FilterConfig. registerGlobalFilters (GlobalFilters. filters); 6 RouteConfig. registerRoutes (RouteTable. routes); 7 BundleConfig. registerBundles (BundleTable. bundles); 8 // Delete xml parsing when the returned value is string, the string is directly returned instead of the json object 9 GlobalConfiguration. configuration. formatters. xmlFormatter. supportedMediaTypes. clear (); 10}
3. Specify the return format
1. The Assembly is required for the new method: System. web. extensions 2 public static HttpResponseMessage ToJson (Object obj) 3 {4 String str; 5 if (obj is String | obj is Char) 6 {7 str = obj. toString (); 8} 9 else10 {11 var serializer = new JavaScriptSerializer (); 12 str = serializer. serialize (obj); 13} 14 var result = new HttpResponseMessage {Content = new StringContent (str, Encoding. getEncoding ("UTF-8"), "application/json")}; 15 return result; 16}
Convert user method to json object output
1 public HttpResponseMessage GetString(string name)2 {3 return ToJson(name);4 }
4. rewrite all output of default implementation class will be parsed into json
1 create Category 2 public class JsonContentNegotiator: IContentNegotiator 3 {4 private readonly JsonMediaTypeFormatter _ jsonFormatter; 5 public partition (JsonMediaTypeFormatter formatter) 6 {7 _ jsonFormatter = formatter; 8} 9 10 public ContentNegotiationResult Negotiate (Type type, HttpRequestMessage request, IEnumerable <MediaTypeFormatter> formatters) 11 {12 var result = new ContentNegotiationResult (_ jsonFormatter, new MediaTypeHeaderValue ("application/json"); 13 return result; 14} 15}
1. In WebApiConfig, rewrite 2 public static void Register (HttpConfiguration config) 3 {4 config. routes. mapHttpRoute (5 name: "DefaultApi", 6 routeTemplate: "api/{controller}/{id}", 7 defaults: new {id = RouteParameter. optional} 8); 9 10 var jsonFormatter = new JsonMediaTypeFormatter (); 11 config. services. replace (typeof (IContentNegotiator), new JsonContentNegotiator (jsonFormatter); 12 13 // uncomment the following code line Supports IQueryable or IQueryable <T> return-type operations to enable query support. 14 // to avoid handling unexpected or malicious queries, use the verification settings on QueryableAttribute to verify incoming queries. 15 // For more information, visit the http://go.microsoft.com/fwlink? LinkId = 279712. 16 // config. enableQuerySupport (); 17 18 // to disable tracing in the application, comment out or delete the following code line 19 // For more information, see: http://www.asp.net/web-api20 config. enableSystemDiagnosticsTracing (); 21}
Spring mvc json directly converts an object to json format and outputs it to the jsp page.
This is easy to use jackson, which comes with spring mvc.
1. Add jackson jar package in web project lib: jackson-core-asl-1.9.9.jar, jackson-mapper-asl-1.9.9.jar
2. Add jackson configuration to applicationContext. xml.
<! -- Json converter --> <bean id = "jsonConverter" class = "org. springframework. http. converter. json. mappingJacksonHttpMessageConverter "> <property name =" supportedMediaTypes "value =" application/json "/> </bean> 3. directly use the annotation method in your action" @ ResponseBody "Automatically convert the returned value to json format
@ Controller @ RequestMapping ("task") public class TaskControl {@ RequestMapping ("getUserById") @ ResponseBody public List getUserById (Integer id) {return this. taskService. getUserById (id) ;}4. The js format of the jsp page is the same as that of the normal ajax format.
Functon getUserById (id) {$. getJSON ("task/getUserById", {id: id}, function (data ){});}
How to obtain the current Area in the filter of net mvc4
ControllerContext. RouteData. DataTokens ["area"]
In View:
ViewContext. RouteData. DataTokens ["area"]
In the request context.
Mobile phone typing is hard, please adopt it.