java and json interchangeable (settlement date of issue)

JSON or JavaScript Object Natation, it is a lightweight data interchange format, is ideal for server and JavaScript interaction. In this paper, to explain under the conversion between java and JSON, in particular, to address each question of the date of conversion experience.
One needs the relevant jar package:
The above packages can be downloaded from the following link:
2, java-"JSON

List<String> list = new ArrayList<String>();
        JSONArray jarr = JSONArray.fromObject(list);
        System.out.println("list->json:" + jarr.toString());

Print Results: list-> json: [ "apple", "orange"]

Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "Michael");
        map.put("baby", new String[] { "Lucy", "Lily" });
        map.put("age", 30);
        JSONObject jo = JSONObject.fromObject(map);
        System.out.println("map->json:" + jo.toString());

Print Results: map-> json: ( "age": 30, "name": "Michael", "baby": [ "Lucy", "Lily"])
3.bean-> JSON

JsonBean bean = new JsonBean();
        bean.setBorn(new Date());
        jo = JSONObject.fromObject(bean);
        System.out.println("bean->json:" + jo.toString());

Print Results: bean-> json: ( "age": 1, "born": ( "date": 10, "day": 3, "hours": 14, "minutes": 14, "month": 2, "seconds": 1, "time": 1268201641228, "timezoneOffset": -480, "year": 110), "name": "NewBaby")
Then you will find it inside the bean object util.Date all of the attributes of this type of conversion out of 11. In actual application process, in most cases we hope to translate into yyyy-MM-dd format, Here's to talk about how to achieve:
First, write a new class JsonDateValueProcessor are as follows:

 * JSON  Date formats to handle  (java Into  JSON)
 * @author Michael sun
public class JsonDateValueProcessor implements JsonValueProcessor {

     * datePattern
    private String datePattern = "yyyy-MM-dd";

     * JsonDateValueProcessor
    public JsonDateValueProcessor() {

     * @param format
    public JsonDateValueProcessor(String format) {
        this.datePattern = format;

     * @param value
     * @param jsonConfig
     * @return Object
    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        return process(value);

     * @param key
     * @param value
     * @param jsonConfig
     * @return Object
    public Object processObjectValue(String key, Object value,
            JsonConfig jsonConfig) {
        return process(value);

     * process
     * @param value
     * @return
    private Object process(Object value) {
        try {
            if (value instanceof Date) {
                SimpleDateFormat sdf = new SimpleDateFormat(datePattern,
                return sdf.format((Date) value);
            return value == null ? "" : value.toString();
        } catch (Exception e) {
            return "";


     * @return the datePattern
    public String getDatePattern() {
        return datePattern;

     * @param pDatePattern the datePattern to set
    public void setDatePattern(String pDatePattern) {
        datePattern = pDatePattern;


Test Code:

JsonBean bean = new JsonBean();
        bean.setBorn(new Date());

        JsonConfig jsonConfig = new JsonConfig();
                new JsonDateValueProcessor());

        JSONObject jo = JSONObject.fromObject(bean, jsonConfig);
        System.out.println("bean->json:" + jo.toString());

Print Results: bean-> json: ( "age": 1, "born": "2010-03-10", "name": "NewBaby")
It can get what we want result.

3, JSON-"java
1. How to json in yyyy-MM-dd conversion of the Bean in the util.Date type:

                new DateMorpher(new String[] { "yyyy-MM-dd" }));

        String jsonStr = "[{\"name\": \"husband\", \"age\": \"26\", \"born\": \"1984-01-12\"},{\"name\": \"wife\", \"age\": \"20\", \"born\": \"1990-05-01\"}]";

        Collection<JsonBean> list = JSONArray.toCollection(JSONArray
                .fromObject(jsonStr), JsonBean.class);
      //DateUtil.getFormatDate(date,fmtstr) Date change string here no longer write code
        for (JsonBean o : list) {
                    .getFormatDate(o.getBorn(), "yyyy-MM-dd"));

Print Results:
2. JSON-"List, Map

String listStr = "[\"apple\",\"orange\"]";
        Collection<String> strlist = JSONArray.toCollection(JSONArray
        for (String str : strlist) {

        String mapStr = "{\"age\":30,\"name\":\"Michael\",\"baby\":[\"Lucy\",\"Lily\"]}";
        Map<String, Object> map = (Map) JSONObject.toBean(JSONObject
                .fromObject(mapStr), Map.class);
        for (Entry<String, Object> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "  " + entry.getValue());

Print Results:
name Michael
age 30
baby [Lucy, Lily]

分类:Java 时间:2009-08-31 人气:364
blog comments powered by Disqus


  • javaBean与Map String,Object 互转 2014-04-15

    1. 为什么要实现javaBean与Map<String,Object>相互转换? 用过spring的都知道spring的MVC框架中有一个BaseCommandController对象,利用这个对象我们就可以很方便的将从客户端传递过来的参数封装到一个JavaBean对象中去,而不需要我们request.getParameter("name");bean.setName(name);了,从而也简化了不少的工作.如果大家用过BeanUtils.populate的话,就知道,这

  • SQL Server datetime format conversion date used 2010-12-20

    We often need to use a variety of for some purposes the date format, of course, we can use string manipulation to construct a variety of date formats, but there are ready-made function why not? SQL Server Chinese version of the default date field is

  • sql server date format conversion method Daquan ---- reproduced 2010-09-08

    sql server date format conversion method Daquan Sql server database in operation, it often will use the date format conversion method, I compiled a frequently used inside SQL Server date format conversion of several methods for later use. Chinese ver

  • Date of query SQL Server date format conversion 2011-02-18

    Date of query SQL Server date format conversion Issues: Often have such a query request, input or produce the calendar control date format yyyy-mm-dd, and database fields are datetime type, that is yyyy-mm-dd hh: mm: ss. If you use between a simple s

  • [SQLServer] date format conversion 2011-06-13

    --SQLSERVER Date format conversion SELECT CONVERT(VARCHAR(20), GETDATE(), 120 ) --2011-06-13 13:54:18 SELECT CONVERT(VARCHAR(10),GETDATE(),120) --2011-06-13 SELECT CONVERT(VARCHAR(12) , GETDATE(), 111 ) --2011/06/13 SELECT CONVERT(VARCHAR(12) , GETDA

  • ext/date/php_date.lo is not a valid libtool object 2013-10-29

    今天在安装php-5.3.10时,make报错: ext/date/php_date.lo is not a valid libtool object. 查看libtool(由ltmain.sh生成)该错误是由于: if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then 语句不成立而后续引起的. 正确的lo文件应该如下: # ext/date/php_dat

  • struts标签绑定Map String, List Map String, Object 2014-04-15

    早先时候已经有一篇写到struts的iterator标签去遍历些基本的集合数据了,比如单个对象的List啊,多个对象的List啊,map等等.最近呢又遇见两种情况,在这里给记录一下,方便自己以后能随时查看,也希望能在一定程度上帮助到大家. 第一种情况是,这里首先有两个表,一个表是客户表(CustomerInfo),一个表是收货人表(TakerInfo),两个表中,都有姓名(name)和电话(cellphone)的属性,根据页面输入的一系列条件,如name,cellphone等去查询两表,得到一个

  • Oracle data types and storage methods (c) the date and time types 2010-08-26

    The third part of the date time type § 3.1 DATE Date Type Oralce used to represent the date and time data types. Fixed occupy 7 bytes. Including the seven attributes: Century century year month day hour minute and second of the month SQL> create tabl

  • Struts2 Data Tags (e) the use of s: date tag and format the date output 2011-01-05

    1.s: date overview of the label s: date tag feature is for date and time, and time with formatting functions. s: date tag attributes and significance of Property name If necessary Type Help format false String Formatted date string name true String D

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C), All Rights Reserved. 版权所有 闽ICP备15018612号

processed in 0.236 (s). 10 q(s)