Convert objects to JSON format in Java and NET

Source: Internet
Author: User

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}]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.