Java和NET中将对象转JSON格式
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}]
补充:软件开发 , Java ,