maven配置:
2.6.5
com.fasterxml.jackson.core
jackson-core
${fasterxml.jackson.version}
com.fasterxml.jackson.core
jackson-databind
${fasterxml.jackson.version}
com.fasterxml.jackson.core
jackson-annotations
${fasterxml.jackson.version}
com.fasterxml.jackson.module
jackson-module-scala_2.11
${fasterxml.jackson.version}
用法:
导入依赖:
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
声明一个转换器:
val mapper = new ObjectMapper() //com.fasterxml.jackson.core
注册为Scala模型:
mapper.registerModule(DefaultScalaModule)
在Spark中使用进行解码:
dataFrame.map { line =>
mapper.readValue(line, classOf[Event])
}.toDF().createOrReplaceTempView("streamEvent")
参考java用例:
微服务中从其他服务获取过来的对象,如果从Object强转为自定义的类型会报错,利用ObjectMapper转换。
ObjectMapper mapper = new ObjectMapper();
DefaultResponse defaultResponse = proxy.getData();
List resources = () defaultResponse.getData(); //这里的场景是:data是一个Object类型的,但是它其实是一个List,想把List中的每个对象分别转成可用的对象
for (int i = 0; i < serviceDateResources.size(); i++) {
Resource resource = mapper.convertValue(resources.get(i), Resource.class); //经过这步处理,resource就是可用的类型了,如果不转化会报错
}
上面转换的过程中,如果返回的字段你不是都需要,需要忽略其中的几个字段,在自定义的类中添加如下
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Resource {
// private Integer orderId; //提供有这个参数,但是不想获取
private Integer otrerFiled;
}
或者下面方法:这两种方法不用添加注解
一:
ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD,Visibility.ANY);
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
二:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ObjectMapper可以实现对象到json等其他格式的互转。如果向将java对象转成Json格式,可以用:
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(object);
会有JsonProcessingException异常,需要自己处理。在转换的过程中,有可能有的属性被设成空就不序列化等的需求,可以在类的属性上或直接在类上加上一下注解。用在属性上就是只针对一个属性,用在类上就是针对类里的所有属性。
@JsonInclude(Include.NON_NULL)
@JsonInclude(Include.Include.ALWAYS) 默认
@JsonInclude(Include.NON_DEFAULT) 属性为默认值不序列化
@JsonInclude(Include.NON_EMPTY) 属性为 空(“”) 或者为 NULL 都不序列化
@JsonInclude(Include.NON_NULL) 属性为NULL 不序列化
json转成Object 及 Object转json
DefaultResponse response = mapper.readValue(result, DefaultResponse.class);
String Json = mapper.writeValueAsString(student1);
mapper.readValue()过程中,如果result中的字段比DefaultResponse字段多会报错,忽略多余的字段在DefaultResponse中添加下面注解。
@JsonIgnoreProperties(ignoreUnknown = true)
可增加如下配置,解决json中属性多于java对象中属性时报错的问题.(吻合Scala用法)
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
XXX xxx = objectMapper.readValue(jsonResult, XXX.class);
maven配置:
com.fasterxml.jackson.core
jackson-databind
2.4.1
org.codehaus.jackson
jackson-jaxrs
1.9.11
代码:
import java.io.IOException;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestJackSon {
// 声明两个转换器
private ObjectMapper objectMapper = null; // 一般使用ObjectMapper就已足够
private JsonGenerator jsonGenerator = null; // 需要关闭
/**
* Java对象转换成JSON_1(objectMapper)
*/
public void test1() {
// 实例化转换器
objectMapper = new ObjectMapper();
// 测试
try {
User user = new User("ZhangSan", 25, "[email protected]");
// 直接输出转化结果到服务台,返回void
System.out.println("直接输出到服务台:");
objectMapper.writeValue(System.out, user); // user可替换为List,Map等等其他类型,都可正常输出
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Java对象转换成JSON_2(objectMapper)
*/
public void test2() {
// 实例化转换器
objectMapper = new ObjectMapper();
// 测试
try {
User user = new User("ZhangSan", 25, "[email protected]");
// 返回String
String json = objectMapper.writeValueAsString(user); // user可替换为List,Map等等其他类型,都可正常输出
System.out.println("返回String:");
System.out.println(json);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Json转Java对象(objectMapper)
*/
public void test3() {
// 实例化转换器
objectMapper = new ObjectMapper();
// 测试
try {
String json = "{\"name\":\"ZhangSan\",\"age\":25,\"emailAddress\":\"[email protected]\"}";
User user = objectMapper.readValue(json, User.class);
System.out.println(user.getName() + " | " + user.getAge() + " | " + user.getEmailAddress());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* jsonGenerator的简单使用
*/
public void test4() {
// 实例化转换器
objectMapper = new ObjectMapper();
try {
jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
User user = new User("ZhangSan", 25, "[email protected]");
// 测试
System.out.println("jsonGenerator:");
jsonGenerator.writeObject(user); //直接输出到控制台
// jsonGenerator需要关闭
if (jsonGenerator != null) {
jsonGenerator.flush();
}
if (!jsonGenerator.isClosed()) {
jsonGenerator.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 测试main
*/
public static void main(String[] args) {
TestJackSon test = new TestJackSon();
test.test4();
}
}
class User {
public String name;
public int age;
public String emailAddress;
/**
* 构造函数
*/
public User(String name, int age, String emailAddress) {
super();
this.name = name;
this.age = age;
this.emailAddress = emailAddress;
}
// getters/setters(略)
}