首先申明所需jar包:
- ezmorph-1.0.6.jar
- jackson-all-1.7.6.jar
- jsoup-1.5.2.jar
一、创建一个实体类Emp.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
package com.hyx.entity; public class Emp { private Integer id; private String name; private Integer dptNo; private String gender; private String duty; public Integer getId() { return id; } public void setId(Integer id) { this .id = id; } public String getName() { return name; } public void setName(String name) { this .name = name; } public Integer getDptNo() { return dptNo; } public void setDptNo(Integer dptNo) { this .dptNo = dptNo; } public String getGender() { return gender; } public void setGender(String gender) { this .gender = gender; } public String getDuty() { return duty; } public void setDuty(String duty) { this .duty = duty; } } |
二、实体类转换为Json
(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
import java.io.IOException; import net.sf.json.JSONObject; import org.apache.struts2.json.JSONException; import org.codehaus.jackson.map.ObjectMapper; import com.hyx.entity.Emp; public class MainTest { public static <T> String objectToJson(T obj) throws JSONException, IOException { ObjectMapper mapper = new ObjectMapper(); // Convert object to JSON string String jsonStr = "" ; try { jsonStr = mapper.writeValueAsString(obj); } catch (IOException e) { throw e; } return JSONObject.fromObject(obj).toString(); } // 主函数 public static void main(String[] args) { Emp emp= new Emp(); emp.setId( 1 ); emp.setName( "张三" ); emp.setGender( "男" ); emp.setDptNo( 001 ); emp.setDuty( "职员" ); String jsonStr= "" ; try { jsonStr=objectToJson(emp); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(jsonStr); } } |
(2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
import net.sf.json.JSONObject; import com.hyx.entity.Emp; public class MainTest { // 主函数 public static void main(String[] args) { Emp emp= new Emp(); emp.setId( 1 ); emp.setName( "张三" ); emp.setGender( "男" ); emp.setDptNo( 001 ); emp.setDuty( "职员" ); JSONObject jsonObject = JSONObject.fromObject(emp); System.out.println(jsonObject); } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/Yasha/p/6268562.html