zoukankan      html  css  js  c++  java
  • 用 Jackson 来处理 JSON

    Jackson 是一个 Java 用来处理 JSON 格式数据的类库,性能非常好。

    首先创建一个User对象类 (User.java)

    package com.sivalabs.json;

    import java.util.Date;

    public class User {

    private String userId;

    private UserName userName;

    private Date dob;

    @Override

    public String toString(){

    return "User [dob=" + dob + ", userId=" + userId + ", userName="+ userName + "]";
    }

    //setters and getters

    }

    UserName.java

    package com.sivalabs.json;

    public class UserName {

    private String firstname;

    private String middlename;

    private String lastname;

    @Override

    public String toString()

    {

    return "UserName [firstname=" + firstname +

    ", lastname=" + lastname+

    ", middlename=" + middlename + "]";

    }

    //setters and getters

    }

    [Java]代码

    //接下来创建User实例,并生成JSON数据
    

    ObjectMapper mapper = new ObjectMapper();

    UserName userName = new UserName();

    userName
    .setFirstname("Katamreddy");

    userName
    .setMiddlename("Siva");

    userName
    .setLastname("PrasadReddy");

    User user = new User();

    user
    .setUserId("1");

    user
    .setUserName(userName);

    user
    .setDob(new Date());

    Writer strWriter = new StringWriter();

    mapper
    .writeValue(strWriter, user);

    String userDataJSON = strWriter.toString();

    System.out.println(userDataJSON);

    执行结果

    {
    "userId":"1",
    "userName":
    {
    "firstname":"Katamreddy",
    "middlename":"Siva",
    "lastname":"PrasadReddy"
    },
    "dob":1300878089906
    }

    接下来进行JSON到Java对象的转换

    String userDataJSON = 
    "{"userId":"100","userName":{"firstname":"K""+
    ","middlename":"Siva","lastname":"Prasad"},"dob":1300878089906}";
    User userFromJSON = mapper.readValue(userDataJSON, User.class);
    System.out.println(userFromJSON);

    时间的格式化处理

    DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
    SerializationConfig serConfig = mapper.getSerializationConfig();
    serConfig
    .setDateFormat(dateFormat);
    DeserializationConfig deserializationConfig = mapper.getDeserializationConfig();
    deserializationConfig
    .setDateFormat(dateFormat);
    mapper
    .configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);

    [Java]代码

    //从文件中读取JSON数据
    User user = mapper.readValue(new File("user.json"), User.class);
        </div>
  • 相关阅读:
    python 访问对象的属性与方法
    python 使用类实列化对象
    python 第一个Python类(创建类)
    python 安装第三方模块
    Redux其实很简单(原理篇)
    JavaScript、ES5和ES6的介绍和区别
    Yes,I know the way to learn Ens !
    移动游戏加载性能和内存管理全解析 学习
    内存耗用:VSS/RSS/PSS/USS
    Android性能测试-内存
  • 原文地址:https://www.cnblogs.com/jpfss/p/9055737.html
Copyright © 2011-2022 走看看