1.1. 下载json-lib.jar
http://sourceforge.net/projects/json-lib/files/json-lib/
1.2. Java对象转换为json
1.2.1. Map对象转换为json
Map2Json.java |
package json; import java.util.HashMap; import java.util.Map; import net.sf.json.JSONArray; public public Map<String, String> map = new HashMap<String, String>(); map.put("姓名", map.put("年龄", map.put("性别", JSONArray jsonArray = JSONArray.fromObject(map); System.out.println(jsonArray.toString()); } } |
运行结果:
[{"性别":"男","姓名":"张三","年龄":"22"}]
1.2.2. List转换为json对象
List2json.java |
package json; import java.util.ArrayList; import java.util.List; import net.sf.json.JSONArray; public class List2Json { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("aa"); list.add("bb"); list.add("cc"); list.add("dd"); JSONArray jsonArray = JSONArray.fromObject(list); System.out.println(jsonArray.toString()); } } |
结果:
["aa","bb","cc","dd"]
1.2.3. Java bean转为json对象
Person.java |
package json; import java.util.Date; public private String private String private private String private Date public String getName() { return } public this.name = name; } public String getSex() { return } public this.sex = sex; } public return } public this.age = age; } public String getAddress() { return } public this.address = address; } public Date getBirthday() { return } public this.birthday = birthday; } public Person(String name, String sex, Date birthday) { super(); this.name = name; this.sex = sex; this.age = age; this.address = address; this.birthday = birthday; } public Person() { super(); // TODO Auto-generated constructor stub } } |
Bean2Json.java |
package json;
import java.util.Date;
import net.sf.json.JSONArray;
public class Bean2Json {
public static void main(String[] args) {
Person person = new Person(); person.setAddress("深圳福田"); person.setAge(22); person.setBirthday(new Date()); person.setName("张三"); person.setSex("男");
JSONArray jsonArray = JSONArray.fromObject(person);
System.out.println(jsonArray.toString());
}
} |
运行结果:
[{"address":"深圳福田","age":22,"birthday":{"date":27,"day":2,"hours":22,"minutes":47,"month":0,"seconds":22,"time":1422370042957,"timezoneOffset":-480,"year":115},"name":"张三","sex":"男"}]
1.3. Json转换为map对象
Json2Map.java |
package json; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import net.sf.json.JSONObject; public public String jsonStr = "{‘性别‘:‘男‘,‘姓名‘:‘张三‘,‘年龄‘:‘22‘}"; JSONObject object = JSONObject.fromObject(jsonStr); Map<String,String> map = new HashMap<String,String>(); Set<String> keySet = object.keySet(); for (String key : keySet) { map.put(key, object.getString(key)); } Set<Entry<String,String>> entrySet = map.entrySet(); for (Entry<String, String> entry : entrySet) { System.out.println(entry.getKey()+":"+entry.getValue()); } } } |
运行结果:
性别:男
姓名:张三
年龄:22