Jackson 框架,轻易转换JSON (包括时间转换)

分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

               

关于jackson中时间字符串的转换中的错误.

[java] view plain copy print ?
  1. "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
  2. "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
  3. "EEE,ddMMMyyyyHH:mm:sszzz"
  4. "yyyy-MM-dd"
当实体中存在Date类型,但是json字符串中是字符串类型

只支持以上几种格式否则报错

[java] view plain copy print ?
  1. org.codehaus.jackson.map.JsonMappingException:Cannotconstructinstanceofjava.util.DatefromStringvalue'19802-22T12:00:00.000-0800':notavalidrepresentation(error:Cannotparsedate"19802-22T12:00:00.000-0800":notcompatiblewithanyofstandardforms("yyyy-MM-dd'T'HH:mm:ss.SSSZ","yyyy-MM-dd'T'HH:mm:ss.SSS'Z'","EEE,ddMMMyyyyHH:mm:sszzz","yyyy-MM-dd"))
  2. at[Source:java.io.StringReader@183f74d;line:1,column:15](throughreferencechain:com.masque.json.Person["birthday"])
  3. atorg.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
  4. atorg.codehaus.jackson.map.deser.StdDeserializationContext.weirdStringException(StdDeserializationContext.java:220)
  5. atorg.codehaus.jackson.map.deser.StdDeserializer._parseDate(StdDeserializer.java:511)
  6. atorg.codehaus.jackson.map.deser.DateDeserializer.deserialize(DateDeserializer.java:26)
  7. atorg.codehaus.jackson.map.deser.DateDeserializer.deserialize(DateDeserializer.java:17)
  8. atorg.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:230)
  9. atorg.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:334)
  10. atorg.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:495)
  11. atorg.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:351)
  12. atorg.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2130)
  13. atorg.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1394)
  14. atcom.masque.json.JacksonTo.main(JacksonTo.java:15)

查了下资料

Letter

Date or Time Component

Presentation

Examples

G

Era designator

Text

AD

y

Year

Year

1996;96

M

Month in year

Month

July;Jul;07

w

Week in year

Number

27

W

Week in month

Number

2

D

Day in year

Number

189

d

Day in month

Number

10

F

Day of week in month

Number

2

E

Day in week

Text

Tuesday;Tue

a

Am/pm marker

Text

PM

H

Hour in day (0-23)

Number

0

k

Hour in day (1-24)

Number

24

K

Hour in am/pm (0-11)

Number

0

h

Hour in am/pm (1-12)

Number

12

m

Minute in hour

Number

30

s

Second in minute

Number

55

S

Millisecond

Number

978

z

Time zone

General time zone

Pacific Standard Time;PST;GMT-08:00

Z

Time zone

RFC 822 time zone

-0800

标准时间格式

Date and Time Pattern

Result

"yyyy.MM.dd G 'at' HH:mm:ss z"

2001.07.04 AD at 12:08:56 PDT

"EEE, MMM d, ''yy"

Wed, Jul 4, '01

"h:mm a"

12:08 PM

"hh 'o''clock' a, zzzz"

12 o'clock PM, Pacific Daylight Time

"K:mm a, z"

0:08 PM, PDT

"yyyyy.MMMMM.dd GGG hh:mm aaa"

02001.July.04 AD 12:08 PM

"EEE, d MMM yyyy HH:mm:ss Z"

Wed, 4 Jul 2001 12:08:56 -0700

"yyMMddHHmmssZ"

010704120856-0700

"yyyy-MM-dd'T'HH:mm:ss.SSSZ"

2001-07-04T12:08:56.235-0700

"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"

2001-07-04T12:08:56.235-07:00

"YYYY-'W'ww-u"

2001-W27-3



Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。

前面有介绍过json-lib这个框架,在线博文:http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html

相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。

一、准备工作

1、 下载依赖库jar包

Jackson的jar all下载地址:http://jackson.codehaus.org/1.7.6/jackson-all-1.7.6.jar

然后在工程中导入这个jar包即可开始工作

官方示例:http://wiki.fasterxml.com/JacksonInFiveMinutes

因为下面的程序是用junit测试用例运行的,所以还得添加junit的jar包。版本是junit-4.2.8

如果你需要转换xml,那么还需要stax2-api.jar

2、 测试类基本代码如下

package com.hoo.test;
 
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.xml.XmlMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.hoo.entity.AccountBean;
 
/**
 * function:Jackson 将java对象转换成JSON字符串,也可以将JSON字符串转换成java对象
 * jar-lib-version: jackson-all-1.6.2
 * jettison-1.0.1
 * @author hoojo
 * @createDate 2010-11-23 下午04:54:53
 * @file JacksonTest.java
 * @package com.hoo.test
 * @project Spring3
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
@SuppressWarnings("unchecked")
public class JacksonTest {
    private JsonGenerator jsonGenerator = null;
    private ObjectMapper objectMapper = null;
    private AccountBean bean = null;
    
    @Before
    public void init() {
        bean = new AccountBean();
        bean.setAddress("china-Guangzhou");
        bean.setEmail("[email protected]");
        bean.setId(1);
        bean.setName("hoojo");
        
        objectMapper = new ObjectMapper();
        try {
            jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @After
    public void destory() {
        try {
            if (jsonGenerator != null) {
                jsonGenerator.flush();
            }
            if (!jsonGenerator.isClosed()) {
                jsonGenerator.close();
            }
            jsonGenerator = null;
            objectMapper = null;
            bean = null;
            System.gc();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3、 所需要的JavaEntity

package com.hoo.entity;
 
public class AccountBean {
    private int id;
    private String name;
    private String email;
    private String address;
    private Birthday birthday;
    
    //getter、setter
    
    @Override
    public String toString() {
        return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
    }
}

Birthday

package com.hoo.entity;
 
public class Birthday {
    private String birthday;
    
    public Birthday(String birthday) {
        super();
        this.birthday = birthday;
    }
 
    //getter、setter
 
    public Birthday() {}
    
    @Override
    public String toString() {
        return this.birthday;
    }
}

二、Java对象转换成JSON

1、 JavaBean(Entity/Model)转换成JSON

/**
 * function:将java对象转换成json字符串
 * @author hoojo
 * @createDate 2010-11-23 下午06:01:10
 */
@Test
public void writeEntityJSON() {
    
    try {
        System.out.println("jsonGenerator");
        //writeObject可以转换java对象,eg:JavaBean/Map/List/Array等
        jsonGenerator.writeObject(bean);    
        System.out.println();
        
        System.out.println("ObjectMapper");
        //writeValue具有和writeObject相同的功能
        objectMapper.writeValue(System.out, bean);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

运行后结果如下:

jsonGenerator

你可能感兴趣的:(Jackson 框架,轻易转换JSON (包括时间转换))