json2.2.3使用-jar包-源码-例子

来源:互联网 发布:数据分析师考试 编辑:程序博客网 时间:2024/05/16 01:21

工程源码 http://pan.baidu.com/s/1eQuGgSU

commons-beanutils-1.7.0.jar

commons-collections-3.2.1.jar
commons-httpclient-3.1.jar
commons-lang-2.3.jar
commons-logging-1.1.1.jar
ezmorph-1.0.3.jar

json-lib-2.2.3-jdk15.jar

json-lib-2.2.3-jdk15.jar


附带junit-4.8.2.jar  进行单元测试


package net.xicp;public class User {private Integer id;private String name;private Integer age;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 getAge() {return age;}public void setAge(Integer age) {this.age = age;}public User(Integer id, String name, Integer age) {super();this.id = id;this.name = name;this.age = age;}@Overridepublic String toString() {return "User [id=" + id + ", name=" + name + ", age=" + age + "]";}public User() {}}
<pre name="code" class="java">package net.xicp.test;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import net.xicp.User;import org.junit.Test;public class JSONObjectTest {/** * 把List集合转成JSON对象 */@Testpublic void testListToJSON(){List<User> users = new ArrayList<User>();User u1 = new User(1001, "张三", 29);User u2 = new User(1002, "李四", 27);User u3 = new User(1003, "王五", 29);users.add(u1);users.add(u2);users.add(u3);JSONArray json = JSONArray.fromObject(users);System.out.println(json.toString());}/** * 把Map集合转成JSON对象 */@Testpublic void testMapToJSON(){Map<String,Object> map = new HashMap<String,Object>();User u1 = new User(1001, "张三", 29);User u2 = new User(1002, "李四", 27);User u3 = new User(1003, "王五", 29);map.put("zhangsan", u1);map.put("lisi", u2);map.put("wangwu", u3);map.put("arr", new String[]{"A","B"});JSONObject json = JSONObject.fromObject(map);System.out.println(json.toString());}/** * 把bean转成JSON对象 */@Testpublic void testBeanToJSON(){User u1 = new User(1001, "张三", 29);JSONObject json = JSONObject.fromObject(u1);System.out.println(json.toString());}/** * 把bean转成JSON对象 */@Testpublic void testArrayToJSON(){String[] strs = {"A","B","C"};JSONArray json = JSONArray.fromObject(strs);System.out.println(json.toString());}/** * 把JSON转成String */@Testpublic void testJsonToString(){JSONObject jsonObj = new JSONObject();jsonObj.put("zhangsan", "张三");jsonObj.put("lisi", "李四");System.out.println(jsonObj.toString());}/** * 把JSON转成bean */@Testpublic void testJsonToBean(){String str = "{\"id\":1001,\"name\":\"张三\",\"age\":25}";JSONObject jsonObj = JSONObject.fromObject(str);User user = (User) JSONObject.toBean(jsonObj, User.class);System.out.println(user);}}


                                             
0 0
原创粉丝点击