Fastjson和jackson序列化和反序列化Json

港控/mmm° 2022-04-02 13:41 344阅读 0赞

先上实体类:​

  1. public class People {
  2. String name;
  3. Integer age;
  4. public String getName() {
  5. return name;
  6. }
  7. public Integer getAge() {
  8. return age;
  9. }
  10. public void setName(String name) {
  11. this.name = name;
  12. }
  13. public void setAge(Integer age) {
  14. this.age = age;
  15. }
  16. @Override
  17. public String toString() {
  18. return "People [name=" + name + ", age=" + age + "]";
  19. }
  20. }

fastjson:

  1. //fastjson
  2. @Test
  3. public void testFastjson() {
  4. People p = new People();
  5. p.setName("zhangsan");
  6. p.setAge(18);
  7. // 对象转json
  8. String jsonStr = JSONObject.toJSONString(p); // {"age":18,"name":"zhangsan"}
  9. // json转对象
  10. People people = JSONObject.parseObject(jsonStr, People.class); // People [name=zhangsan, age=18]
  11. }

jackson:

  1. //jackson objectMapper
  2. @Test
  3. public void testJackson() throws Exception {
  4. People p = new People();
  5. p.setName("lisi");
  6. p.setAge(81);
  7. // objectMapper是jackson的核心类,基本所有的操作都由它来实现
  8. ObjectMapper om = new ObjectMapper();
  9. // 对象转json
  10. String jsonStr = om.writeValueAsString(p); //{"name":"lisi","age":81}
  11. // json转对象
  12. People people = om.readValue(jsonStr, People.class); //People [name=lisi, age=81]
  13. }

发表评论

表情:
评论列表 (有 0 条评论,344人围观)

还没有评论,来说两句吧...

相关阅读