import os import datetime import time from flask import Flask, g, request, json from flask.json import JSONEncoder class CustomJsonEncoder(JSONEncoder): # 針對日期自訂 Json 轉換 def default(self, obj): if isinstance(obj, datetime.date): return obj.isoformat().replace('T', ' ') return super().default(obj) app = Flask(__name__) app.json_encoder = CustomJsonEncoder app.config['JSON_AS_ASCII'] = False # 返回結果可以正確顯示中文
2023-02-21 10:13
[Python] Flask 自訂日期的 Json 轉換
2015-03-01 20:14
[Java] Jackson Json Parser 筆記
Object Encode / Decode
Parser to Map
Encode Date
參考自:FasterXML/jackson-databind · GitHub
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
訂閱:
文章 (Atom)