package com.e6.ztest;
import java.util.Date;
import org.codehaus.jackson.map.annotate.JsonSerialize;
public class Birthday {
private Date dateBirth;
private String birthdayTx;
public String getBirthdayTx() {
return birthdayTx;
}
public void setBirthdayTx(String birthdayTx) {
this.birthdayTx = birthdayTx;
}
@JsonSerialize(using = JsonDateSerializer.class)
public Date getDateBirth() {
return dateBirth;
}
public void setDateBirth(Date dateBirth) {
this.dateBirth = dateBirth;
}
public Birthday() {
}
}
package com.e6.ztest;
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;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Birthday getBirthday() {
return birthday;
}
public void setBirthday(Birthday birthday) {
this.birthday = birthday;
}
}
package com.e6.ztest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
public class JsonDateSerializer extends JsonSerializer {
@Override
public void serialize(Date arg0, JsonGenerator arg1, SerializerProvider arg2)
throws IOException, JsonProcessingException {
//"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(arg0);
arg1.writeString(formattedDate);
}
}
package com.e6.ztest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
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.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.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JsonTest {
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();
}
}
@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的writeObject方法和ObjectMapper的writeValue方法完成对Java对象的转换,二者传递的参数及构造的方式不同;JsonGenerator的创建依赖于ObjectMapper对象。也就是说如果你要使用JsonGenerator来转换JSON,那么你必须创建一个ObjectMapper。但是你用ObjectMapper来转换JSON,则不需要JSONGenerator。
//
// objectMapper的writeValue方法可以将一个Java对象转换成JSON。这个方法的参数一,需要提供一个输出流,转换后可以通过这个流来输出转换后的内容。或是提供一个File,将转换后的内容写入到File中。当然,这个参数也可以接收一个JSONGenerator,然后通过JSONGenerator来输出转换后的信息。第二个参数是将要被转换的Java对象。如果用三个参数的方法,那么是一个Config。这个config可以提供一些转换时的规则,过指定的Java对象的某些属性进行过滤或转换等。
//
// 2、 将Map集合转换成Json字符串
/**
* function:将map转换成json字符串
* @author hoojo
* @createDate 2010-11-23 下午06:05:26
*/
@Test
public void writeMapJSON() {
try {
Map map = new HashMap();
map.put("name", bean.getName());
map.put("account", bean);
bean = new AccountBean();
bean.setAddress("china-Beijin");
bean.setEmail("[email protected]");
Birthday bir = new Birthday();
bir.setBirthdayTx("1988/01/30");
bir.setDateBirth(new Date());
bean.setBirthday(bir);
map.put("account2", bean);
System.out.println("jsonGenerator");
jsonGenerator.writeObject(map);
System.out.println("");
System.out.println("objectMapper");
objectMapper.writeValue(System.out, map);
} catch (IOException e) {
e.printStackTrace();
}
}
// 转换后结果如下:
//jsonGenerator
// {"account2":{"id":0,"name":null,"email":"[email protected]","address":"china-Beijin","birthday":{"dateBirth":"2014-03-25T00:33:09.709+0800","birthdayTx":"1988/01/30"}},"name":"hoojo","account":{"id":1,"name":"hoojo","email":"[email protected]","address":"china-Guangzhou","birthday":null}}
// objectMapper
// {"account2":{"id":0,"name":null,"email":"[email protected]","address":"china-Beijin","birthday":{"dateBirth":"2014-03-25T00:33:09.709+0800","birthdayTx":"1988/01/30"}},"name":"hoojo","account":{"id":1,"name":"hoojo","email":"[email protected]","address":"china-Guangzhou","birthday":null}}
// 3、 将List集合转换成json
/**
* function:将list集合转换成json字符串
* @author hoojo
* @createDate 2010-11-23 下午06:05:59
*/
@Test
public void writeListJSON() {
try {
List list = new ArrayList();
list.add(bean);
bean = new AccountBean();
bean.setId(2);
bean.setAddress("address2");
bean.setEmail("email2");
bean.setName("haha2");
list.add(bean);
System.out.println("jsonGenerator");
//list转换成JSON字符串
jsonGenerator.writeObject(list);
System.out.println();
System.out.println("ObjectMapper");
//用objectMapper直接返回list转换成的JSON字符串
System.out.println("1###" + objectMapper.writeValueAsString(list));
System.out.print("2###");
//objectMapper list转换成JSON字符串
objectMapper.writeValue(System.out, list);
} catch (IOException e) {
e.printStackTrace();
}
}
// 结果如下:
//
// jsonGenerator
// [{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"[email protected]"},
// {"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
// ObjectMapper
// 1###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"[email protected]"},
// {"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
// 2###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"[email protected]"},
// {"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
// 外面就是多了个[]中括号;同样Array也可以转换,转换的JSON和上面的结果是一样的,这里就不再转换了。~.~
//
// 4、下面来看看jackson提供的一些类型,用这些类型完成json转换;如果你使用这些类型转换JSON的话,那么你即使没有JavaBean(Entity)也可以完成复杂的Java类型的JSON转换。下面用到这些类型构建一个复杂的Java对象,并完成JSON转换。
@Test
public void writeOthersJSON() {
try {
String[] arr = { "a", "b", "c" };
System.out.println("jsonGenerator");
String str = "hello world jackson!";
//byte
jsonGenerator.writeBinary(str.getBytes());
//boolean
jsonGenerator.writeBoolean(true);
//null
jsonGenerator.writeNull();
//float
jsonGenerator.writeNumber(2.2f);
//char
jsonGenerator.writeRaw("c");
//String
jsonGenerator.writeRaw(str, 5, 10);
//String
jsonGenerator.writeRawValue(str, 5, 5);
//String
jsonGenerator.writeString(str);
jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str));
System.out.println();
//Object
jsonGenerator.writeStartObject();//{
jsonGenerator.writeObjectFieldStart("user");//user:{
jsonGenerator.writeStringField("name", "jackson");//name:jackson
jsonGenerator.writeBooleanField("sex", true);//sex:true
jsonGenerator.writeNumberField("age", 22);//age:22
jsonGenerator.writeEndObject();//}
jsonGenerator.writeArrayFieldStart("infos");//infos:[
jsonGenerator.writeNumber(22);//22
jsonGenerator.writeString("this is array");//this is array
jsonGenerator.writeEndArray();//]
jsonGenerator.writeEndObject();//}
AccountBean bean = new AccountBean();
bean.setAddress("address");
bean.setEmail("email");
bean.setId(1);
bean.setName("haha");
//complex Object
jsonGenerator.writeStartObject();//{
jsonGenerator.writeObjectField("user", bean);//user:{bean}
jsonGenerator.writeObjectField("infos", arr);//infos:[array]
jsonGenerator.writeEndObject();//}
} catch (Exception e) {
e.printStackTrace();
}
}
// 运行后,结果如下:
//
// jsonGenerator
// "aGVsbG8gd29ybGQgamFja3NvbiE=" true null 2.2c world jac worl "hello world jackson!" "hello world jackson!"
// {"user":{"name":"jackson","sex":true,"age":22},"infos":[22,"this is array"]}
// {"user":{"address":"address","name":"haha","id":1,"birthday":null,"email":"email"},"infos":["a","b","c"]}
// 怎么样?构造的json字符串和输出的结果是一致的吧。关键看懂用JSONGenerator提供的方法,完成一个Object的构建。
//
// 三、JSON转换成Java对象
//
// 1、 将json字符串转换成JavaBean对象
@Test
public void readJson2Entity() {
String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\",\"birthday\":{\"birthdayTx\":\"1988/01/30\",\"dateBirth\":\"2014-03-24\"}}";
try {
AccountBean acc = objectMapper.readValue(json, AccountBean.class);
System.out.println(acc.getName());
System.out.println(acc.getBirthday().getDateBirth().toString());
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 很简单,用到了ObjectMapper这个对象的readValue这个方法,这个方法需要提供2个参数。第一个参数就是解析的JSON字符串,第二个参数是即将将这个JSON解析成什么Java对象,Java对象的类型。
//当然,还有其他相同签名方法,如果你有兴趣可以一一尝试使用方法,
//当然使用的方法和当前使用的方法大同小异。运行后,结果如下:
//
// haha
// Mon Mar 24 08:00:00 CST 2014
// 2、 将json字符串转换成List
只支持以上几种格式否则报错
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 |
只支持以上几种格式否则报错
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 |