2015-03-01

[Java] Jackson Json Parser 筆記

Object Encode / Decode
import java.util.Arrays;
import java.util.Date;

import com.fasterxml.jackson.databind.ObjectMapper;

class Album {
    private int id;
    private String title;
    private Date date;
    private String[] list;

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }

    public Date getDate() { return date; }
    public void setDate(Date date) { this.date = date; }

    public String[] getList() { return list; }
    public void setList(String[] list) { this.list = list; }

    @Override
    public String toString() {
        return String.format("id: %s, title: %s, date: %s, list: %s",
            id, title, date, Arrays.toString(list)
        );
    }
}

public class TestJackson {

    public static void main(String[] args) throws Exception {
        Album album = new Album();
        album.setId(1);
        album.setTitle("Go Go Go!");;
        album.setDate(new Date());
        album.setList(new String[]{"Love", "Despair"});

        ObjectMapper jsonMapper = new ObjectMapper();

        String json = jsonMapper.writeValueAsString(album);
        System.out.println(json);
        // {"id":1,"title":"Go Go Go!","date":1425211903948,"list":["Love","Despair"]}

        Album album2 = jsonMapper.readValue(json, Album.class);
        System.out.println(album2);
        // id: 1, title: Go Go Go!, date: Sun Mar 01 20:11:43 CST 2015, list: [Love, Despair]
    }
}


Parser to Map
ObjectMapper jsonMapper = new ObjectMapper();
Map<String,String> map;

map = jsonMapper.readValue(
    "{\"name\":\"jax\", \"age\":\"31\"}",
    new TypeReference<HashMap<String,String>>(){}
);
System.out.println(map);
// {age=31, name=jax}


jsonMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
jsonMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

map = jsonMapper.readValue(
    "{name:'jax', age:'31'}",
    new TypeReference<HashMap<String,String>>(){}
);
System.out.println(map);
// {age=31, name=jax}


Encode Date
Date date = new Date();

String json;
ObjectMapper jsonMapper = new ObjectMapper();

json = jsonMapper.writeValueAsString(date);
System.out.println(json);
// 1425211840183


jsonMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

json = jsonMapper.writeValueAsString(date);
System.out.println(json);
// "2015-03-01T12:10:40.183+0000"

參考自:FasterXML/jackson-databind · GitHub

0 回應: