使用fastjson将java 实体类转换为json很方便,但是直接用在普通的Scala实体类上生成的json是空的"{}",需要使用scala.beans.BeanProperty注解修饰一下scala类字段。
一,依赖
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<fastjson.version>1.2.54</fastjson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
</dependencies>
二,java实例
public class JavaUser {
private String userName;
private String userSex;
private int id;
public JavaUser(String userName,String userSex,int id){
this.userName=userName;
this.userSex=userSex;
this.id=id;
}
public String getUserName() {
return userName;
}
public String getUserSex() {
return userSex;
}
}
import com.alibaba.fastjson.*;
public class JavaTest {
public static void main(String[] args) {
System.out.println(JSON.toJSONString(new JavaUser("zhangsan","man",1)));
}
}
没有定义getter的字段,不会输出到json中。(public 修饰的字段可以)
private int id;
三,scala实例
import scala.beans.BeanProperty
class ScalaUser(@BeanProperty val userName:String,@BeanProperty val userSex:String,_id:Int) {
val id:Int=_id
}
import com.alibaba.fastjson.JSON
object ScalaTest {
def main(args: Array[String]): Unit = {
println(JSON.toJSONString(new ScalaUser("lisi", "woman",2),JSON.DEFAULT_GENERATE_FEATURE))
}
}
使用@BeanProperty修饰的类成员会输出到json中。
四,原因
Scala中代码 var类型字段=private变量+getter+setter; val类型字段=private变量+getter; 但是命名方式与java不同,getter为字段名,setter为**字段名_()**的形式,与fastjson要求的命名方式不一致。BeanProperty则能提供java风格的getter和setter。
package scala.beans
/** When attached to a field, this annotation adds a setter and a getter
* method following the Java Bean convention. For example:
* {{{
* @BeanProperty
* var status = ""
* }}}
* adds the following methods to the class:
* {{{
* def setStatus(s: String) { this.status = s }
* def getStatus: String = this.status
* }}}
* For fields of type `Boolean`, if you need a getter named `isStatus`,
* use the `scala.beans.BooleanBeanProperty` annotation instead.
*/
@scala.annotation.meta.field
class BeanProperty extends scala.annotation.StaticAnnotation
|