java使用json技术
导包
封装数组
package com.iotek.json;
public class User {
private String userName;
private String password;
private String address;
public User() {
// TODO Auto-generated constructor stub
}
public User(String userName, String password, String address) {
super();
this.userName = userName;
this.password = password;
this.address = address;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [userName=" + userName + ", password=" + password
+ ", address=" + address + "]";
}
}
测试
package com.iotek.json;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class TestJson {
public static void main(String[] args) {
// TODO Auto-generated method stub
// TestJsonObject();
//TestJsonArray();
//使用键值对的方式创建json对象
Map<String,User> map=new HashMap();
User u1=new User("liayin1","fendou1","上海");
User u2=new User("liayin2","fendou2","上海");
map.put("user1", u1);
map.put("user2", u2);
JSONArray jarray=new JSONArray();
jarray.add(map);
System.out.println(jarray);
}
//创建json对象数组
private static void TestJsonArray() {
JSONArray jarray=new JSONArray();
jarray.add(new User("liayin1","fendou1","上海"));
jarray.add(new User("liayin2","fendou2","上海"));
jarray.add(new User("liayin3","fendou3","上海"));
System.out.println(jarray.toString());
}
//创建json单一对象
private static void TestJsonObject() {
JSONObject jsonobj=new JSONObject();
jsonobj.put("name", "容儿");
jsonobj.put("age", 22);
jsonobj.put("address", "上海");
System.out.println(jsonobj.toString()); //json格式字符串
}
}