我们知道jfinal关联查询的结果是无法通过fastjson完整转化为json串的,因为一些关联属性并没有get set方法。
它原声不支持,我们就要创造条件让他支持
思路:重写fastjson的类,增加处理activerecord的逻辑
框架 : springboot + jfinal dao
1.重写fastjson的方法
package com.sj.configuration.json; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import org.springframework.http.HttpOutputMessage; import org.springframework.http.converter.HttpMessageNotWritableException; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import com.jfinal.kit.JsonKit; import com.jfinal.plugin.activerecord.Model; public class JFastJsonHttpMessageConverter extends FastJsonHttpMessageConverter{ public static final Charset UTF8 = Charset.forName("UTF-8"); @Override protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { if(object instanceof Model) { OutputStream out = outputMessage.getBody(); out.write(JsonKit.toJson(object).getBytes(UTF8)); }else { super.writeInternal(object, outputMessage); } } }
主要是这一段
if(object instanceof Model) {}
2.注册json处理器
package com.sj.configuration.app; import java.util.ArrayList; import java.util.List; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.sj.configuration.json.JFastJsonHttpMessageConverter; @Configuration public class AppConfiguration { @Bean public HttpMessageConverters fastJsonHttpMessageConventers() { JFastJsonHttpMessageConverter converter = new JFastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig(); List<MediaType> mediaTypes = new ArrayList<MediaType>(); mediaTypes.add(MediaType.APPLICATION_JSON_UTF8); config.setSerializerFeatures(SerializerFeature.PrettyFormat); converter.setSupportedMediaTypes(mediaTypes); converter.setFastJsonConfig(config); HttpMessageConverter<?> converter1 = converter; return new HttpMessageConverters(converter1); } }
这里面就用到了我们自己写的
JFastJsonHttpMessageConverter
我们看一下效果
package com.sj.contorller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.sj.model.SysUser; @RestController public class TestController { @RequestMapping("/user") public SysUser user() { SysUser user = new SysUser(); user.setUsername("name"); user.setUserid("id"); user.put("xx", "abc"); return user; } }
大家看到 xx也被打印出来了
大功告成
里面还附赠一个basedao可供使用