package open_exe; public class User { private int id;
private String name;
private String gender; public User() { } public User(int id, String name, String gender) {
this.id = id;
this.name = name;
this.gender = gender;
} 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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
package open_exe; import java.util.ArrayList;
import java.util.List; import net.sf.json.JSONArray;
import net.sf.json.JSONObject; public class Jsonzhuanhuan{
static String objectToJsonString(){
JSONObject jsonObject = JSONObject.fromObject(new User(1, "张三", "男"));//java对象转json对象
return jsonObject.toString();
} static void jsonStringToObject(String jsonString){
JSONObject jsonObject = JSONObject.fromObject(jsonString);
User user = (User)JSONObject.toBean(jsonObject, User.class);//json对象转java对象需要注意 json对象属性名称首字母为大写会出错
System.out.println(user.getName());
} /**
* 将Java集合转换为Json字符串
*
*
*/
static String collectionToJsonString(){
List<User> userList = new ArrayList<User>();
userList.add(new User(1, "张三", "男"));
userList.add(new User(2, "李四", "女"));
userList.add(new User(3, "王五", "男"));
JSONArray jsonArray = JSONArray.fromObject(userList);
return jsonArray.toString();
String[] arr = {"asd","dfgd","asd","234"};//补充内容 数组转json
JSONArray jsonarray = JSONArray.fromObject(arr);
} /**
* 将Json字符串转换为Java集合
*
*
*/
static void jsonStringToCollection(String jsonString){
JSONArray jsonArray = JSONArray.fromObject(jsonString);
@SuppressWarnings("unchecked")
List<User> userList = (List<User>)JSONArray.toCollection(jsonArray, User.class);
for (User user : userList) {
System.out.println(user.getName());
}
}
public static void main(String[] args) {
System.out.println(objectToJsonString());//对象转json
jsonStringToObject(objectToJsonString());//json转对象 System.out.println(collectionToJsonString());
jsonStringToCollection(collectionToJsonString());
}
}