java其他類型數據轉換爲Json數據

1、創建類Json

importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;

importnet.sf.json.JSONArray;
importnet.sf.json.JSONObject;

//將Java數據轉換成Json數據 
public class Json{
public static voidmain(String[] args) {
Json json = newJson();
json.array2json();//從數組轉換到JSON
System.out.println("----------------------------------");
json.string2Json();//從字符串轉換到JSON
System.out.println("----------------------------------");
json.list2json();//從列表轉換到JSON
System.out.println("----------------------------------");
json.createJson();//從一般數據轉換到JSON
System.out.println("----------------------------------");
json.map2json();//從map轉換到JSON
System.out.println("----------------------------------");
json.bean2json();//從Bean轉換到JSON
System.out.println("----------------------------------");
json.json2bean();//從JSON轉換到Bean
System.out.println("----------------------------------");
}

// 數組轉換成Json
public void array2json(){
String[] numbers = { "one","two", "three", "four", "five" };
JSONArray ja =JSONArray.fromObject(numbers);
System.out.println(ja);
}

//字符串轉換成Json
public void string2Json(){
String json ="{name:\"jack\",sex:\"male\",age:23}";
JSONObject jo =JSONObject.fromObject(json);
System.out.println(jo);
}

// 從集合轉換成Json
public void list2json(){
List<String> list= newArrayList<String>();
list.add("first");
list.add("second");
list.add("third");
list.add("fourth");
JSONArray ja =JSONArray.fromObject(list);
System.out.println(ja);
}

// 一般數據轉換成Json
public void createJson(){
JSONArray ja =JSONArray.fromObject("['json','is','easy']");
System.out.println(ja);
}

// map轉換成Json
public void map2json(){
Map<String,Object>map = new HashMap<String,Object>();
map.put("name","Howard");
map.put("bool",Boolean.TRUE);
map.put("integer", newInteger(1));
map.put("array", new String[] {"a", "b", "c", "d" });
map.put("function","function(i){ return this.arr[i]; }");
JSONObject jo =JSONObject.fromObject(map);
System.out.println(jo);
}

// Bean轉換成Json
public void bean2json(){
// fromObject--從其它對象轉化成JSON對象
Student student=newStudent("Alice",21);
JSONObject jo =JSONObject.fromObject(student);
System.out.println(jo);
}

//Json轉換成Bean
public void json2bean(){
String strJson ="{name:\"Jack\",age:23}";
JSONObject jo =JSONObject.fromObject(strJson);
Student student = (Student)JSONObject.toBean(jo, Student.class);
System.out.println(student.getName()+","+student.getAge());
}
}

2、創建類Student

public class Student{
private Stringname;
private int age;
public Student(){
}

public Student(String name, intage) {
super();
this.name = name;
this.age = age;
}

public String getName(){
return name;
}

public void setName(Stringname) {
this.name = name;
}

public int getAge(){
return age;
}

public void setAge(int age){
this.age = age;
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章