第一步:下载Jackson的jar包http://pan.baidu.com/s/1qXHwtQ0
第二步:在gradle中导入jar包
第三步:创建ObjectMapper对象的单例
JacksonMapper.java
public class JacksonMapper {
private static final ObjectMapper mapper = new ObjectMapper(); private JacksonMapper() {
} public static ObjectMapper getInstance() {
return mapper;
}
}
第四步:创建工具类JSONUtil.java
public class JSONUtil { public static String getJsonString(Object object) throws Exception {
return JacksonMapper.getInstance().writeValueAsString(object);
} public static Object toObject(String jsonString, Class cls) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(jsonString, cls);
}
}
第五步:使用
Birthday birthday = new Birthday(2000, 4, 28);
Person person = new Person("zhang san", 29, birthday);
try {
Log.d(TAG, "onCreate: " + JSONUtil.getJsonString(person));
} catch (Exception e) {
Log.e(TAG, "onCreate: " + e.toString());
e.printStackTrace();
} String jsonStr = "{\"name\":\"zhang san\",\"birthday\":{\"day\":28,\"month\":4,\"year\":2000},\"age\":29}";
try {
Log.d(TAG, "onCreate: " + JSONUtil.toObject(jsonStr, Person.class));
} catch (Exception e) {
e.printStackTrace();
} 第六步:Birthday.java
public class Birthday {
private int year;
private int month;
private int day; public int getYear() {
return year;
} public void setYear(int year) {
this.year = year;
} public int getMonth() {
return month;
} public void setMonth(int month) {
this.month = month;
} public int getDay() {
return day;
} public void setDay(int day) {
this.day = day;
} public Birthday() {
super();
} public Birthday(int year, int month, int day) {
super();
this.year = year;
this.month = month;
this.day = day;
} @Override
public String toString() {
return "Birthday [year=" + year + ", month=" + month + ", day=" + day
+ "]";
}
}
Person.java
public class Person {
private String name;
private int age;
private String number;
private Birthday birthday; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Birthday getBirthday() {
return birthday;
} public void setBirthday(Birthday birthday) {
this.birthday = birthday;
} public Person() {
super();
} public void setNumber(String number) {
this.number = number;
} public String getNumber() {
return number;
} public Person(String name, int age, Birthday birthday) {
super();
this.name = name;
this.age = age;
this.birthday = birthday;
} @Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", birthday="
+ birthday + "]";
}
结果如下: