此处将为大家介绍关于FastJsonJsonView的详细内容,此外,我们还将为您介绍关于Android使用fastjson找不到fastjson包问题的解决方法、com.alibaba.fastjs
此处将为大家介绍关于FastJsonJsonView的详细内容,此外,我们还将为您介绍关于Android 使用fastjson找不到fastjson包问题的解决方法、com.alibaba.fastjson.support.spring.FastJsonJsonView的实例源码、com.fasterxml.jackson.annotation.JsonView的实例源码、FASTJSON 2.0 发布,FASTJSON 项目的重要升级的有用信息。
本文目录一览:- FastJsonJsonView
- Android 使用fastjson找不到fastjson包问题的解决方法
- com.alibaba.fastjson.support.spring.FastJsonJsonView的实例源码
- com.fasterxml.jackson.annotation.JsonView的实例源码
- FASTJSON 2.0 发布,FASTJSON 项目的重要升级
FastJsonJsonView
#FastJsonJsonView #index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="view/json.html">json</a>
</body>
</html>
只是一个简单的跳转页面 ##web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>spring_dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:conf/springmvc-beanname.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring_dispatcher</servlet-name>
<url-pattern>/view/*</url-pattern>
</servlet-mapping>
</web-app>
web.xml中使用了springmvc-beanname.xml配置文件,设置的过滤方式是路径过滤。拦截以view开头的路径。
##springmvc-beanname.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<bean/>
<bean name="/json.html"/>
<!-- ViewResolver 默认使用的是InternalResourceViewResolver viewClass使用的是JstlView-->
<!--
<bean>
<property name="order" value="1" />
<property name="contentType" value="text/html; charset=utf-8" />
<property name="prefix" value="/jsp" />
<property name="suffix" value=".jsp" />
</bean>
-->
<!-- 静态资源目录映射 -->
<!-- <mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/themes/**" location="/themes/" />
<mvc:resources mapping="/dwz.frag.xml" location="/dwz.frag.xml" />
<mvc:resources mapping="/index.html" location="/index.html" />
-->
</beans>
urlmapping使用的是BeanNameUrlHandlerMapping,ViewResolver使用的是默认的InternalResourceViewResolve,当然viewClass使用的也是默认的JstlView。这里值得注意的是因为Dispatcher的servlet-mapping中拦截的是路径/view/*,所以bean中的name配置的是/json.html而不是/view/json.html
##JsonController
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
public class JsonController implements Controller{
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
FastJsonJsonView view = new FastJsonJsonView();
ResultModel model = new ResultModel();
ModelAndView mv = new ModelAndView(view,model);
return mv;
}
}
final class ResultModel extends HashMap<String,Object>{
private static final long serialVersionUID = 2933536235393803231L;
private String statusCode = "200";
private String message = "操作成功";
private String navTabId = "";
private String rel ="";
private String callbackType = "closeCurrent";
private String forwardUrl = "";
public ResultModel(){
this.put("statusCode", statusCode);
this.put("message", message);
this.put("navTabId", navTabId);
this.put("rel", rel);
this.put("callbackType", callbackType);
this.put("forwardUrl", forwardUrl);
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.put("statusCode", statusCode);
this.statusCode = statusCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.put("message", message);
this.message = message;
}
public String getNavTabId() {
return navTabId;
}
public void setNavTabId(String navTabId) {
this.put("navTabId", navTabId);
this.navTabId = navTabId;
}
public String getRel() {
return rel;
}
public void setRel(String rel) {
this.put("rel", rel);
this.rel = rel;
}
public String getCallbackType() {
return callbackType;
}
public void setCallbackType(String callbackType) {
this.put("callbackType", callbackType);
this.callbackType = callbackType;
}
public String getForwardUrl() {
return forwardUrl;
}
public void setForwardUrl(String forwardUrl) {
this.put("forwardUrl", forwardUrl);
this.forwardUrl = forwardUrl;
}
}
因为使用的是BeanNameUrlHandlerMapping,所以需要实现Controller接口(或者继承其子类,如AbstractController)。在handleRequest方法中返回的ModelAndView中View使用FastJsonJsonView就可以了。
##附录pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.freemethod</groupId>
<artifactId>web-learning</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>web-learning Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring_version>4.1.6.RELEASE</spring_version>
</properties>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring_version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring_version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring_version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring_version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring_version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring_version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring_version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring_version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring_version}</version>
</dependency>
<!-- servlet jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
</dependencies>
</project>
Android 使用fastjson找不到fastjson包问题的解决方法
JSON解析库有很多,诸如Jackson,Json-lib,org.json,Gson和fastjson等,但是fastjson以其解析速度最快而脱颖而出。详细的测试地址如下:
https://github.com/eishay/jvm-serializers/wiki/Staging-Results
fastjson是国内alibaba公司的wenshao开发的,项目Git地址:
https://github.com/alibaba/fastjson
今天测试了下发现fastjson挺好用,比Android自带的org.json库要好用多了。当然我没有对fastjson的性能进行测试,只是因为Android自带的不太好。
在普通的java项目下,只需要导入fastjson.jar就可以,无需依赖其他包,这一点相比json-lib要好多,json-lib依赖五六个包。但是将fastjson.jar导入Android工程后,在使用时会出现 java.lang.NoClassDefFoundError:can''t find com.alibaba.fastjson.JSON等错误消息。
初步认为是与Android自带的org.json冲突。于是Build Path->Configure Build Path->Order And Export下将fastjson.jar上调至Android xx.jar上(xx为android 版本号)。再运行工程,这个错误不再出现了,奇迹般的没问题了。
然后现在再调整fastjson.jar和Android.jar顺序也不会出现can''t not find com.alibaba.fastjson的错误,不知道为何,继续看。
文章Java虚拟机类加载顺序讲解了java 虚拟机加载class和jar包的顺序。
bootstrap classloader ->extension classloader->system classloader
其中bootstrap引导类加载器;
extension classloader扩展类加载器,它负责加载JRE的扩展目录(JAVA_HOME/jre/lib/ext或者由java.ext.dirs系统属性指定的)中JAR的类包;
system classloader系统(也称为应用)类加载器,它负责在JVM被启动时,加载来自在命令java中的-classpath或者java.class.path系统属性或者 CLASSPATH操作系统属性所指定的JAR类包和类路径.
该文中还有一句话是这么说的,应该能解决我们的疑惑:
“此外类加载还采用了cache机制,也就是如果 cache中保存了这个Class就直接返回它,如果没有才从文件中读取和转换成Class,并存入cache,这就是为什么我们修改了Class但是必须重新启动JVM才能生效的原因。”
我想应该是Android虚拟机中已经有了fastjson的cache了,所以导致如何更改项目的fastjson.jar和Android.jar顺序都不会有任何反应。我的理解是这样,不知道对不对,欢迎大侠指正。
解释到这里,也解决了我另外一个疑问,就是在Android的工程中新建一个java类,并生成main方法,然后Run->Java Application. 结果会出现如下的错误:
#
# A fatal error has been detected by the Java Runtime Environment:
#
# Internal Error (classFileParser.cpp:3494), pid=5940, tid=5632
# Error: ShouldNotReachHere()
这个问题的产生就是和bootstrap classloard 有关了,文件上右键Run As->Run Configuration选择Java Application下的这个Java类,然后选择右侧的Classpath标签页下有两个目录,分别是Bootstrap Entries 和 User Entries。
Android工程中Bootsrap下默认的是Android Classpath Container,而Java则应该是JRE System Library。所以按照该文Error: ShouldNotReachHere()的解决方法,更改就好了。
com.alibaba.fastjson.support.spring.FastJsonJsonView的实例源码
@Test public void test_jsonp() throws Exception { FastJsonjsonView view = new FastJsonjsonView(); Assert.assertNotNull(view.getFastJsonConfig()); view.setFastJsonConfig(new FastJsonConfig()); view.setExtractValueFromSingleKeyModel(true); view.setdisableCaching(true); MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("callback","queryName"); MockHttpServletResponse response = new MockHttpServletResponse(); Assert.assertEquals(true,view.isExtractValueFromSingleKeyModel()); view.render(Collections.singletonMap("abc","cde中文"),request,response); String contentAsstring = response.getContentAsstring(); int contentLength = response.getContentLength(); Assert.assertEquals(contentLength,contentAsstring.getBytes(view.getFastJsonConfig().getCharset().name()).length); }
@RequestMapping(value = "/getProgress/{fileKey}",method = RequestMethod.GET) public ModelAndView getProgress(@PathVariable("fileKey") String fileKey,Map<String,Object> model) { if (PROCESS_MAP.containsKey(fileKey)) { Tuple2Unit<Integer,Integer> progresstuple = PROCESS_MAP.get(fileKey); model.put("status","processing"); model.put("precent",progresstuple.getP1() * 100 / progresstuple.getP2()); } else { model.put("status","OK"); } return new ModelAndView(new FastJsonjsonView()); }
@Override public void configureViewResolvers(ViewResolverRegistry registry) { FastJsonjsonView fastJsonjsonView = new FastJsonjsonView(); registry.enableContentNegotiation(fastJsonjsonView); }
@SuppressWarnings("deprecation") public void test_0() throws Exception { FastJsonjsonView view = new FastJsonjsonView(); Assert.assertEquals(Charset.forName("UTF-8"),view.getCharset()); view.setCharset(Charset.forName("GBK")); Assert.assertEquals(Charset.forName("GBK"),view.getCharset()); Assert.assertNull(view.getDateFormat()); view.setDateFormat("yyyyMMdd"); Assert.assertNotNull(view.getFeatures()); Assert.assertEquals(1,view.getFeatures().length); view.setSerializerFeature(SerializerFeature.browserCompatible); Assert.assertEquals(1,view.getFeatures().length); Assert.assertEquals(SerializerFeature.browserCompatible,view.getFeatures()[0]); view.setFeatures(SerializerFeature.disableCheckSpecialChar,SerializerFeature.sortField); Assert.assertEquals(2,view.getFeatures().length); Assert.assertEquals(SerializerFeature.disableCheckSpecialChar,view.getFeatures()[0]); Assert.assertEquals(SerializerFeature.sortField,view.getFeatures()[1]); view.setFilters(serializefilter); Assert.assertEquals(1,view.getFilters().length); Assert.assertEquals(serializefilter,view.getFilters()[0]); Map<String,Object> model = new HashMap<String,Object>(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); view.render(model,response); view.setRenderedAttributes(null); view.setCharset(Charset.forName("UTF-8")); view.render(model,response); view.setUpdateContentLength(true); view.setFeatures(SerializerFeature.browserCompatible); view.render(model,response); view.setCharset(Charset.forName("GBK")); view.render(Collections.singletonMap("abc","cde"),response); view.setdisableCaching(false); view.setUpdateContentLength(false); view.render(model,response); view.setRenderedAttributes(new HashSet<String>(Collections.singletonList("abc"))); view.render(Collections.singletonMap("abc",response); }
public void test_1() throws Exception { FastJsonjsonView view = new FastJsonjsonView(); Assert.assertNotNull(view.getFastJsonConfig()); view.setFastJsonConfig(new FastJsonConfig()); Map<String,Object>(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); view.render(model,response); view.setRenderedAttributes(null); view.render(model,response); view.setUpdateContentLength(true); view.render(model,response); view.setExtractValueFromSingleKeyModel(true); Assert.assertEquals(true,view.isExtractValueFromSingleKeyModel()); view.setdisableCaching(true); view.render(Collections.singletonMap("abc",response); }
@Test public void test_jsonp_invalidparam() throws Exception { FastJsonjsonView view = new FastJsonjsonView(); Assert.assertNotNull(view.getFastJsonConfig()); view.setFastJsonConfig(new FastJsonConfig()); view.setExtractValueFromSingleKeyModel(true); view.setdisableCaching(true); MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("callback","-methodName"); MockHttpServletResponse response = new MockHttpServletResponse(); Assert.assertEquals(true,view.isExtractValueFromSingleKeyModel()); view.render(Collections.singletonMap("doesn't matter",Collections.singletonMap("abc","cde中文")),response); String contentAsstring = response.getContentAsstring(); Assert.assertTrue(contentAsstring.startsWith("{\"abc\":\"cde中文\"}")); }
com.fasterxml.jackson.annotation.JsonView的实例源码
@Override public void propertyField(JFieldVar field,JDefinedClass clazz,String propertyName,JsonNode propertyNode) { field.annotate(JsonProperty.class).param("value",propertyName); if (field.type().erasure().equals(field.type().owner().ref(Set.class))) { field.annotate(JsonDeserialize.class).param("as",LinkedHashSet.class); } if (propertyNode.has("javaJsonView")) { field.annotate(JsonView.class).param( "value",field.type().owner().ref(propertyNode.get("javaJsonView").asText())); } if (propertyNode.has("description")) { field.annotate(JsonPropertyDescription.class).param("value",propertyNode.get("description").asText()); } }
@GetMapping(value = "/{slug}") @JsonView(View.Public.class) public ResponseEntity<Post> getPost(@PathVariable("slug") String slug) { log.debug("get postsinfo by slug @" + slug); Post post = this.postRepository.findBySlug(slug).orElseThrow( () -> { return new PostNotFoundException(slug); } ); log.debug("get post @" + post); return new ResponseEntity<>(post,HttpStatus.OK); }
@JsonView(JsonViews.Basique.class) @RequestMapping(value = "/api/sprint/delete/{id}",method = RequestMethod.DELETE,produces = "application/json") public ResponseEntity<Sprint> deleteSprint(@PathVariable("id") Long id) { LOGGER.debug("ApiController - deleteSprint"); Sprint sprint = null; if(sprintService.exists(id)) { sprint = sprintService.findOneById(id); sprintService.deleteOneById(sprint.getId()); return new ResponseEntity<Sprint>(sprint,HttpStatus.ACCEPTED); } return new ResponseEntity<Sprint>(sprint,HttpStatus.NOT_FOUND); }
@JsonView(JsonViews.Basique.class) @RequestMapping(value = "/api/sprint/{idSprint}/story/{idStory}",method = RequestMethod.POST,produces = "application/json") public ResponseEntity<Sprint> linkSprintIdWithStoryId(@PathVariable Long idSprint,@PathVariable Long idStory) { LOGGER.debug("ApiController - linkSprintIdWithStoryId"); Story story = storyService.findOneByIdWithAll(idStory); Sprint sprint = sprintService.findOneByIdWithAll(idSprint); if(null==sprint ||null ==story) { return new ResponseEntity<Sprint>(sprint,HttpStatus.NOT_FOUND); } story.setStorySprint(sprint); story = storyService.save(story); sprint = sprintService.findOneByIdWithAll(idSprint); return new ResponseEntity<Sprint>(sprint,HttpStatus.CREATED); }
@JsonView(JsonViews.Project.class) @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/api/project/details",method = {RequestMethod.GET,RequestMethod.POST},produces = "application/json") public List<Project> showProjectsDetails() { LOGGER.debug("ApiController - showProjectsDetails"); return projectService.findAllWithAll(); }
@JsonView(JsonViews.Basique.class) @RequestMapping(value = "/api/user/add",produces = "application/json") public ResponseEntity<User> sendUser(@RequestBody User user) { LOGGER.debug("ApiController - sendUser"); if(!userService.exists(user.getEmail())) { userService.save(user); LOGGER.debug("ApiController - sendUser - User créé"); return new ResponseEntity<User>(user,HttpStatus.CREATED); } else { LOGGER.debug("ApiController - sendUser - User déjà existant"); return new ResponseEntity<User>(user,HttpStatus.CONFLICT); } }
@JsonView(JsonViews.Basique.class) @RequestMapping(value = "/api/story/update/{idStory}",produces = "application/json") public ResponseEntity<Story> updateStory(@PathVariable Long idStory,@RequestBody Story story,@RequestParam Long idSprint) { LOGGER.debug("ApiController - updateStory"); if(idSprint != null) { Sprint sprint = sprintService.findOneById(idSprint); if(null==sprint) { LOGGER.debug("ApiController - updateStory - Sprint inexistant"); return new ResponseEntity<Story>(story,HttpStatus.NOT_FOUND); } story.setStorySprint(sprint); } storyService.updateStory(idStory,story); LOGGER.debug("ApiController - updateStory - Story maj"); return new ResponseEntity<Story>(story,HttpStatus.ACCEPTED); }
@JsonView(JsonViews.Basique.class) @RequestMapping(value = "/api/story/add/sprint/{idSprint}",produces = "application/json") public ResponseEntity<Story> sendStoryWithSprintId(@PathVariable Long idSprint,@RequestBody Story story) { LOGGER.debug("ApiController - sendStoryWithSprintId"); Sprint sprint = sprintService.findOneById(idSprint); if(null==sprint) { LOGGER.debug("ApiController - sendStoryWithSprintId - Sprint inexistant"); return new ResponseEntity<Story>(story,HttpStatus.NOT_FOUND); } if(story.getStatus()==null) story.setStatus(StoryStatus.Todo); story = storyService.save(story); story.setStorySprint(sprint); story = storyService.save(story); LOGGER.debug("ApiController - sendStoryWithSprintId - Story créé"); return new ResponseEntity<Story>(story,HttpStatus.CREATED); }
@JsonView(JsonViews.Basique.class) @RequestMapping(value = "/api/task/delete/{id}",produces = "application/json") public ResponseEntity<Task> deleteTask(@PathVariable("id") Long id) { LOGGER.debug("ApiController - deleteTask"); Task task = null; if(taskService.exists(id)) { task = taskService.findOneById(id); taskService.deleteOneById(task.getId()); return new ResponseEntity<Task>(task,HttpStatus.ACCEPTED); } return new ResponseEntity<Task>(task,HttpStatus.NOT_FOUND); }
@JsonView(Views.Public.class) @RequestMapping(value = "/answer/user/{name}",method = RequestMethod.GET) public ResponseEntity<?> getAnswersByUser(@PathVariable("name") String name) { User user = userService.getByUsername(name); if (user == null) { return new ResponseEntity(HttpStatus.NO_CONTENT); } List<Answer> answers = answerService.getByUser(user); if (answers.isEmpty()) { return new ResponseEntity(HttpStatus.NO_CONTENT); } return new ResponseEntity<List<Answer>>(answers,HttpStatus.OK); }
@JsonView(Views.Public.class) @RequestMapping(value = "/questions/user/{name}",method = RequestMethod.GET) public ResponseEntity<?> getQuestionsByUser(@PathVariable("name") String name) { User user = userService.getByUsername(name); if (user == null) { return new ResponseEntity(HttpStatus.NO_CONTENT); } List<Question> questions = questionService.getByUser(user); if (questions.isEmpty()) { return new ResponseEntity(HttpStatus.NO_CONTENT); } return new ResponseEntity<List<Question>>(questions,HttpStatus.OK); }
@JsonView(Views.Public.class) @RequestMapping(value = "/questions/tag/{name}",method = RequestMethod.GET) public ResponseEntity<?> getQuestionsByTag(@PathVariable("name") String name) { Tag tag = tagService.getByName(name); if (tag == null) { return new ResponseEntity(HttpStatus.NO_CONTENT); } List<Question> questions = questionService.getByTag(tag); if (questions.isEmpty()) { return new ResponseEntity(HttpStatus.NO_CONTENT); } return new ResponseEntity<List<Question>>(questions,HttpStatus.OK); }
@JsonView(Views.Public.class) @RequestMapping(value = "/login",method = RequestMethod.POST) public ResponseEntity<?> login(@RequestBody LoginModel data) { User user = userService.getByUsername(data.getUsername()); if (user == null) { return new ResponseEntity(new LoginResponseBody(false,null,"User with that name isn't exist"),HttpStatus.OK); } if (!Objects.equals(user.getpassword(),MD5.getHash(data.getpassword()))) { return new ResponseEntity(new LoginResponseBody(false,"wrong_password"),HttpStatus.OK); } String token = Jwts.builder() .setSubject(data.getUsername()) .signWith(SignatureAlgorithm.HS512,key) .compact(); return new ResponseEntity(new LoginResponseBody(true,token),HttpStatus.OK); }
@JsonView(Views.Public.class) @RequestMapping(value = "/register",method = RequestMethod.POST) public ResponseEntity<?> register(@RequestBody LoginModel data) { User user = userService.getByUsername(data.getUsername()); if (user != null) { return new ResponseEntity(new LoginResponseBody(false,"User with that name has already existed"),HttpStatus.OK); } User newUser = new User(data.getUsername(),MD5.getHash(data.getpassword()),new Date(),"active",0); userService.addUser(newUser); String token = Jwts.builder() .setSubject(newUser.getUsername()) .signWith(SignatureAlgorithm.HS512,HttpStatus.OK); }
@POST @Produces("application/json") @JsonView(RestrictedViews.Member.class) @MinRole(Role.ADMIN) @Path("/admin-create-user") public Object admincreateuser(@ObjectParam User newUser) { if (empty(newUser.getEmail())) { newUser.setEmail(newUser.getUsername()); } else if (empty(newUser.getUsername())) { newUser.setUsername(newUser.getEmail()); } IUser user = SafeMerger.with() .nonEmpty("email","username","displayName","role") .optional("familyName","givenname") .merge(newUser); IUser existing = UserController.instance().forEmail(user.getEmail()); if (existing != null) { throw new ClientException("A user with that email address already exists."); } user.setApproved(true); UserController.instance().createuser(user); return user; }
@GET @Path("/users-table") @MinRole(Role.ADMIN) @Produces("application/json") @JsonView(RestrictedViews.Owner.class) public Pager usersTable(@QueryParam("page") Integer page,@QueryParam("withDeleted") Boolean withDeleted) { Map<String,Object> ctx = map(); if (page == null || page < 1) { page = 1; } withDeleted = or(withDeleted,false); FilterChain chain = UserController.instance().filterChain(); if (withDeleted) { chain = chain.includeDeleted(); } Pager pager = chain.sort("email","ASC").pager(page,100); return pager; }
/** * Determine a Jackson serialization view based on the given conversion hint. * @param conversionHint the conversion hint Object as passed into the * converter for the current conversion attempt * @return the serialization view class,or {@code null} if none * @since 4.2 */ protected Class<?> getSerializationView(Object conversionHint) { if (conversionHint instanceof MethodParameter) { MethodParameter param = (MethodParameter) conversionHint; JsonView annotation = (param.getParameterIndex() >= 0 ? param.getParameterannotation(JsonView.class) : param.getmethodAnnotation(JsonView.class)); if (annotation != null) { return extractViewClass(annotation,conversionHint); } } else if (conversionHint instanceof JsonView) { return extractViewClass((JsonView) conversionHint,conversionHint); } else if (conversionHint instanceof Class) { return (Class) conversionHint; } // No JSON view specified... return null; }
@Test public void renderSimpleBeanWithJsonView() throws Exception { Object bean = new TestBeanSimple(); Map<String,Object> model = new HashMap<String,Object>(); model.put("bindingResult",mock(BindingResult.class,"binding_result")); model.put("foo",bean); model.put(JsonView.class.getName(),MyJacksonView1.class); view.setUpdateContentLength(true); view.render(model,request,response); String content = response.getContentAsstring(); assertTrue(content.length() > 0); assertEquals(content.length(),response.getContentLength()); assertTrue(content.contains("foo")); assertFalse(content.contains("boo")); assertFalse(content.contains(JsonView.class.getName())); }
@Test public void renderSimpleBeanWithJsonView() throws Exception { Object bean = new TestBeanSimple(); Map<String,response.getContentLength()); assertTrue(content.contains("foo")); assertFalse(content.contains("boo")); assertFalse(content.contains(JsonView.class.getName())); }
@JsonView(ModelBase.API.class) @RequestMapping(method=RequestMethod.POST) public ResponseEntity<?> create(@AuthenticationPrincipal User user,@Valid @modelattribute TaskForm form,Errors errors) { Task task; if(errors.hasErrors()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors.toString()); } try { task = new Task(); task.setPriority(Task.TaskPriority.norMAL); task.setBelongsTo(user); task.setBelongsToName(user.getName()); task.setBelongsToEmail(user.getEmail()); taskService.save(form.push(task)); } catch (DataAccessException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex); } return ResponseEntity.ok(task); }
@JsonView(ModelBase.API.class) @RequestMapping(value="/{id:[0-9]+}",method=RequestMethod.POST) public ResponseEntity<?> update(@PathVariable("id") Long id,Errors errors) { Task task; if(errors.hasErrors()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors.toString()); } try { task = taskService.findOne(id); taskService.save(form.push(task)); } catch (DataAccessException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex); } return ResponseEntity.ok(task); }
@ApiOperation(value = "Primary Health Check",notes = "The response JSON will contain a message and the results of checking the health of " + "primary dependencies,although stack traces will be excluded.",response = HealthDto.class) @ApiResponses(value = { @ApiResponse(code = 503,message = "unhealthy",response = HealthDto.class),@ApiResponse(code = 200,message = "healthy",response = HealthDto.class)}) @GET @Produces(MediaType.APPLICATION_JSON) @JsonView(HealthJsonViews.Primary.class) Response getPrimaryHealthCheck();
@ApiOperation(value = "Availability Check for Dependency",notes = "Invokes the basic availability check on the given dependency. " + "The response code will match the code returned by the dependency,and will be " + "omitted from the JSON.",response = HealthDependencyDto.class) @ApiResponses(value = { @ApiResponse(code = 503,response = HealthDependencyDto.class),response = HealthDependencyDto.class)}) @GET @Produces(MediaType.APPLICATION_JSON) @JsonView(HealthJsonViews.Dependency.class) @Path("/{name}") Response getDependencyAvailabilityCheck(@PathParam("name") String name);
@ApiOperation(value = "Basic Availability Check",notes = "Always returns 200. The JSON will only include the message field.",message = "unhealthy"),message = "healthy")}) @GET @Produces(MediaType.APPLICATION_JSON) @JsonView(HealthJsonViews.Availability.class) HealthDto getBasicAvailabilityCheck();
@ApiOperation(value = "Diagnostic Health Check",notes = "The response JSON will contain all available diagnostic details and the results of " + "checking the health of all dependencies.",response = HealthDto.class)}) @GET @Produces(MediaType.APPLICATION_JSON) @JsonView(HealthJsonViews.Diagnostic.class) Response getDiagnosticHealthCheck();
@JsonView(JsonViews.Basique.class) @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/api/sprint",produces = "application/json") public List<Sprint> showSprints() { LOGGER.debug("ApiController - showSprints"); return sprintService.findAll(); }
@JsonView(JsonViews.Sprint.class) @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/api/sprint/details",produces = "application/json") public List<Sprint> showSprintsDetails() { LOGGER.debug("ApiController - showSprintsDetails"); return sprintService.findAllWithAll(); }
@JsonView(JsonViews.Basique.class) @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/api/sprint/{id}",produces = "application/json") public ResponseEntity<Sprint> showSprint(@PathVariable Long id) { LOGGER.debug("ApiController - showSprint"); Sprint sprint = null; if(sprintService.exists(id)) { sprint = sprintService.findOneById(id); return new ResponseEntity<Sprint>(sprint,HttpStatus.OK); } return new ResponseEntity<Sprint>(sprint,HttpStatus.NOT_FOUND); }
@JsonView(JsonViews.Sprint.class) @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/api/sprint/{id}/details",produces = "application/json") public ResponseEntity<Sprint> showSprintWithAll(@PathVariable Long id) { LOGGER.debug("ApiController - showSprint"); Sprint sprint = null; if(sprintService.exists(id)) { sprint = sprintService.findOneByIdWithAll(id); return new ResponseEntity<Sprint>(sprint,HttpStatus.NOT_FOUND); }
@JsonView(JsonViews.Basique.class) @RequestMapping(value = "/api/sprint/add",produces = "application/json") public ResponseEntity<Sprint> sendSprint(@RequestBody Sprint sprint) { LOGGER.debug("ApiController - sendSprint"); sprint = sprintService.save(sprint); LOGGER.debug("ApiController - sendSprint - Sprint créé"); return new ResponseEntity<Sprint>(sprint,HttpStatus.CREATED); }
@JsonView(JsonViews.Basique.class) @RequestMapping(value = "/api/sprint/add/project/{idProject}",produces = "application/json") public ResponseEntity<Sprint> sendSprintLinkedToProject(@RequestBody Sprint sprint,@PathVariable Long idProject) { LOGGER.debug("ApiController - sendSprintLinkedToProject"); Project project = projectService.findOneById(idProject); if(project==null) return new ResponseEntity<Sprint>(sprint,HttpStatus.NOT_FOUND); sprint.setSprintProject(project); sprintService.save(sprint); LOGGER.debug("ApiController - sendSprintLinkedToProject - Sprint créé et lié à un projet"); return new ResponseEntity<Sprint>(sprint,HttpStatus.CREATED); }
@JsonView(JsonViews.Basique.class) @RequestMapping(value = "/api/sprint/update/{idSprint}",produces = "application/json") public ResponseEntity<Sprint> updateSprint(@PathVariable Long idSprint,@RequestBody Sprint sprint) { LOGGER.debug("ApiController - updateSprint"); sprintService.updateSprint(idSprint,sprint); LOGGER.debug("ApiController - updateSprint - Project maj"); return new ResponseEntity<Sprint>(sprint,HttpStatus.ACCEPTED); }
@JsonView(JsonViews.Basique.class) @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/api/sprint/project/{idProject}",produces = "application/json") public Set<Sprint> showSprintsAssociatedToThisProject(@PathVariable Long idProject) { LOGGER.debug("ApiController - showSprintsAssociatedToThisProject"); Set<Sprint> sprints = sprintService.findBySprintProject(idProject); return sprints; }
@JsonView(JsonViews.Basique.class) @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/api/project",produces = "application/json") public List<Project> showProjects() { LOGGER.debug("ApiController - showProjects"); return projectService.findAll(); }
@JsonView(JsonViews.Basique.class) @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/api/project/{id}",produces = "application/json") public ResponseEntity<Project> showProject(@PathVariable Long id) { LOGGER.debug("ApiController - showProject"); Project project = null; if(projectService.exists(id)) { project = projectService.findOneById(id); return new ResponseEntity<Project>(project,HttpStatus.OK); } return new ResponseEntity<Project>(project,HttpStatus.NOT_FOUND); }
@JsonView(JsonViews.Project.class) @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/api/project/{id}/details",produces = "application/json") public ResponseEntity<Project> showProjectWithAll(@PathVariable Long id) { LOGGER.debug("ApiController - showProjectWithAll"); Project project = null; if(projectService.exists(id)) { project = projectService.findOneByIdWithAll(id); return new ResponseEntity<Project>(project,HttpStatus.NOT_FOUND); }
@JsonView(JsonViews.Basique.class) @RequestMapping(value = "/api/project/add",produces = "application/json") public ResponseEntity<Project> sendProject(@RequestBody Project project) { LOGGER.debug("ApiController - sendProject"); project = projectService.save(project); LOGGER.debug("ApiController - sendProject - Projet créé"); return new ResponseEntity<Project>(project,HttpStatus.CREATED); }
@JsonView(JsonViews.Basique.class) @RequestMapping(value = "/api/project/update/{idProject}",produces = "application/json") public ResponseEntity<Project> updateProject(@PathVariable Long idProject,@RequestBody Project project) { LOGGER.debug("ApiController - updateProject"); projectService.updateProject(idProject,project); LOGGER.debug("ApiController - updateProject - Project maj"); return new ResponseEntity<Project>(project,HttpStatus.ACCEPTED); }
@JsonView(JsonViews.Basique.class) @RequestMapping(value = "/api/project/delete/{id}",produces = "application/json") public ResponseEntity<Project> deleteProject(@PathVariable("id") Long id) { LOGGER.debug("ApiController - deleteProject"); Project project = null; if(projectService.exists(id)) { project = projectService.findOneById(id); projectService.deleteOneById(id); return new ResponseEntity<Project>(project,HttpStatus.ACCEPTED); } return new ResponseEntity<Project>(project,HttpStatus.NOT_FOUND); }
FASTJSON 2.0 发布,FASTJSON 项目的重要升级
FASTJSON 2.0 是 FASTJSON 项目的重要升级,目标是为下一个十年提供一个高性能的 JSON 库,同一套 API 支持 JSON/JSONB 两种协议,JSONPath 是一等公民,支持全量解析和部分解析,支持 Java 服务端、客户端 Android、大数据场景。
1. 介绍
- FASJTONS2 代码 https://github.com/alibaba/fastjson2/releases/tag/2.0.1
- JSONB 格式文档 https://github.com/alibaba/fastjson2/wiki/jsonb_format_cn
- FASTJSON 2 性能有了很大提升,具体性能数据看这里 https://github.com/alibaba/fastjson2/wiki/fastjson_benchmark
2. 使用前准备
2.1 Maven依赖
在fastjson 2.0中,groupId和1.x不一样,是com.alibaba.fastjson2
<dependency> <groupId>com.alibaba.fastjson2</groupId> <artifactId>fastjson2</artifactId> <version>2.0.1</version> </dependency>
https://repo1.maven.org/maven2/com/alibaba/fastjson2/fastjson2/
2.2
如果原来使用fastjson 1.2.x版本,可以使用兼容包,兼容包不能保证100%兼容,请仔细测试验证,发现问题请及时反馈。
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.1</version> </dependency>
2.2 常用类和方法
在fastjson 2.0中,package和1.x不一样,是com.alibaba.fastjson2。如果你之前用的是fastjson1,大多数情况直接更包名就即可。
package com.alibaba.fastjson2; class JSON { // 将字符串解析成JSONObject static JSONObject parseObject(String str); // 将字符串解析成JSONArray static JSONArray parseArray(String str); // 将字符串解析成Java对象 static T parseObject(byte[] utf8Bytes, Class<T> objectClass); // 将Java对象输出成字符串 static String toJSONString(Object object); // 将Java对象输出成UT8编码的byte[] static byte[] toJSONBytes(Object object); } class JSONB { // 将jsonb格式的byte[]解析成Java对象 static T parseObject(byte[] jsonbBytes, Class<T> objectClass); // 将Java对象输出成jsonb格式的byte[] static byte[] toBytes(Object object); } class JSONObject { Object get(String key); int getIntValue(String key); Integer getInteger(String key); long getLongValue(String key); Long getLong(String key); T getObject(String key, Class<T> objectClass); // 将JSONObject对象转换为Java对象 T toJavaObject(Class<T> objectClass); } class JSONArray { Object get(int index); int getIntValue(int index); Integer getInteger(int index); long getLongValue(int index); Long getLong(int index); T getObject(int index, Class<T> objectClass); } class JSONPath { // 构造JSONPath static JSONPath of(String path); // 根据path直接解析输入,会部分解析优化,不会全部解析 Object extract(JSONReader jsonReader); // 根据path对对象求值 Object eval(Object rootObject); } class JSONReader { // 构造基于String输入的JSONReader static JSONReader of(String str); // 构造基于ut8编码byte数组输入的JSONReader static JSONReader of(byte[] utf8Bytes); // 构造基于char[]输入的JSONReader static JSONReader of(char[] chars); // 构造基于json格式byte数组输入的JSONReader static JSONReader ofJSONB(byte[] jsonbBytes) }
3. 读取JSON对象
String str = "{\"id\":123}"; JSONObject jsonObject = JSON.parseObject(str); int id = jsonObject.getIntValue("id");
String str = "[\"id\", 123]"; JSONArray jsonArray = JSON.parseArray(str); String name = jsonArray.getString(0); int id = jsonArray.getIntValue(1);
4. 将JavaBean对象生成JSON
4.1 将JavaBean对象生成JSON格式的字符串
class Product { public int id; public String name; } Product product = new Product(); product.id = 1001; product.name = "DataWorks"; JSON.toJSONString(product); // 生成如下的结果 { "id" : 1001, "name" : "DataWorks" } JSON.toJSONString(product, JSONWriter.Feature.BeanToArray); // 生成如下的结果 [123, "DataWorks"]
4.2 将JavaBean对象生成UTF8编码的byte[]
Product product = ...; byte[] utf8JSONBytes = JSON.toJSONBytes(product);
4.3 将JavaBean对象生成JSONB格式的byte[]
Product product = ...; byte[] jsonbBytes = JSONB.toBytes(product); byte[] jsonbBytes = JSONB.toBytes(product, JSONWriter.Feature.BeanToArray);
5. 读取JavaBean
5.1 将字符串读取成JavaBean
String str = "{\"id\":123}"; Product product = JSON.parseObject(str, Product.class);
5.2 将UTF8编码的byte[]读取成JavaBean
byte[] utf8Bytes = "{\"id\":123}".getBytes(StandardCharsets.UTF_8); Product product = JSON.parseObject(utf8Bytes, Product.class);
5.3 将JSONB数据读取成JavaBean
byte[] jsonbBytes = ... Product product = JSONB.parseObject(jsonbBytes, Product.class); Product product = JSONB.parseObject(jsonbBytes, Product.class, JSONReader.Feature.SupportBeanArrayMapping);
6. 使用JSONPath
6.1 使用JSONPath部分读取数据
String str = ...; JSONPath path = JSONPath.of("$.id"); // 缓存起来重复使用能提升性能 JSONReader parser = JSONReader.of(str); Object result = path.extract(parser);
6.2 使用JSONPath读取部分utf8Bytes的数据
byte[] utf8Bytes = ...; JSONPath path = JSONPath.of("$.id"); // 缓存起来重复使用能提升性能 JSONReader parser = JSONReader.of(utf8Bytes); Object result = path.extract(parser);
6.3 使用JSONPath读取部分jsonbBytes的数据
byte[] jsonbBytes = ...; JSONPath path = JSONPath.of("$.id"); // 缓存起来重复使用能提升性能 JSONReader parser = JSONReader.ofJSONB(jsonbBytes); // 注意,这是利用ofJSONB方法 Object result = path.extract(parser);
详情可查看:https://github.com/alibaba/fastjson2/releases
今天关于FastJsonJsonView的分享就到这里,希望大家有所收获,若想了解更多关于Android 使用fastjson找不到fastjson包问题的解决方法、com.alibaba.fastjson.support.spring.FastJsonJsonView的实例源码、com.fasterxml.jackson.annotation.JsonView的实例源码、FASTJSON 2.0 发布,FASTJSON 项目的重要升级等相关知识,可以在本站进行查询。
本文标签: