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

3 回應:

terror bird kibble id 提到...

I know this is an old vid, but I'm doing a GET/POST. For simplicity, my post just uses JsonGenerator to create my json file.
My question(s):
A. How do I POST(add) for multiple objects that have an inner object (Multiple users as per your example) .
B. How do I read those back out?

Any assistance would be great as I've been pouring over docs for days now and my brain hurts.

胡忠晞 提到...

I am not familiar with JsonGenerator

not sore after workout 提到...

Are you able to use Maven Update to auto generate the json classes? In enterprise application development, if you are using the jackson gen might not be possible since the json file is huge......... Also, since there is still bugs like the image .... you will need to manually change them. Once it changed them, 30 mins later you have another build....... Too much work...