Java中將對象轉JSON格式
1.導包:
2.編寫實體類:
public class StudVo {
int id;
String name;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
int age;
public StudVo(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
}
3.測試類:
public class T1 {
/**
* @param args
*/
public static void main(String[] args) {
List<StudVo> list=new ArrayList<StudVo>();
list.add(new StudVo(1, “haha1”, 22));
list.add(new StudVo(2, “haha2”, 22));
list.add(new StudVo(3, “haha3”, 22));
System.out.println(net.sf.json.JSONSerializer.toJSON(list));
}
}
4.測試結果
[{“id”:1,”age”:22,”name”:”haha1″},{“id”:2,”age”:22,”name”:”haha2″},{“id”:3,”age”:22,”name”:”haha3″}]
.NET中將對象轉換為JSON(VS2008+)
1. 實體類
public class StudVo
{
public int Id { get; set; }
public String Name { get; set; }
public int Age { get; set; }
}
2. 引命名空間
using System.Web.Script.Serialization;
3. 測試類
JavaScriptSerializer js = new JavaScriptSerializer();
var list = new List<StudVo> {
new StudVo{Id=1,Name=”Haha1″,Age=22},
new StudVo{Id=2,Name=”Haha2″,Age=22},
new StudVo{Id=3,Name=”Haha3″,Age=22}
};
Response.Write(js.Serialize(list));
4. 測試結果
[{“Id”:1,”Name”:”Haha1″,”Age”:22},{“Id”:2,”Name”:”Haha2″,”Age”:22},{“Id”:3,”Name”:”Haha3″,”Age”:22}]