Convert objects to JSON format in Java
1. Import package:
2. Compile the entity class:
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. Test class:
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. Test Results
[{"Id": 1, "age": 22, "name": "haha1" },{ "id": 2, "age": 22, "name ": "haha2" },{ "id": 3, "age": 22, "name": "haha3"}]
. NET converts an object to JSON (VS2008 +)
1. entity class
Public class StudVo
{
Public int Id {get; set ;}
Public String Name {get; set ;}
Public int Age {get; set ;}
}
2. Reference namespace
Using System. Web. Script. Serialization;
3. Test class
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. Test Results
[{"Id": 1, "Name": "Haha1", "Age": 22 },{ "Id": 2, "Name": "Haha2 ", "Age": 22 },{ "Id": 3, "Name": "Haha3", "Age": 22}]