说明:jackson介绍和maven配置在第一节说过了,有不明白的同学可以翻一翻第一节
参考项目:https://github.com/bigbeef/cppba-jackson
开源地址:https://github.com/bigbeef
个人博客:http://blog.cppba.com
1.编写测试代码
package com.cppba.jackson;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
public class StringToObject {
public static void main(String[] args) throws IOException {
String jsonString = "{\"id\":\"1\",\"name\":\"bigbeef\",\"list\":[{\"str\":\"str1\",\"integer\":\"1\"}," +
"{\"str\":\"str2\",\"integer\":\"2\"}]}";
ObjectMapper objectMapper = new ObjectMapper();
MyObject myObject = objectMapper.readValue(jsonString, MyObject.class);
System.out.println(myObject.toString());
}
}
class MyObject{
@JsonProperty("id")
private String id;
@JsonProperty("name")
private String name;
@JsonProperty("list")
private List<MyListProject> list;
@Override
public String toString() {
return "MyObject{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", list=" + list +
'}';
}
}
class MyListProject{
@JsonProperty("str")
private String str;
@JsonProperty("integer")
private Integer integer;
@Override
public String toString() {
return "MyListProject{" +
"str='" + str + '\'' +
", integer=" + integer +
'}';
}
}
2.运行结果
3.用途
字符串转自定义类这种方式非常常见,比如在做微信开发、调用第三方接口时,返回的json字符串基本都是这种方式,如果你学到了这一节的方法,你的开发效率会提高很多!