JSON---Java object conversions

Source: Internet
Author: User

Jsonoject.parseobject (string str, target object. Class);//Convert JSON string to object

Jsonoject.tojsonstring (object);//Convert object to JSON string.

Http://www.cnblogs.com/free-dom/p/5801866.html

Create an entity class student

 Public classStudent {//namePrivateString name;//AgePrivateString age;//AddressPrivateString address; PublicString GetName () {returnname;} Public voidsetName (String name) { This. Name =name;} PublicString getage () {returnAge ;} Public voidsetage (String age) { This. Age =Age ;} PublicString getaddress () {returnaddress;} Public voidsetaddress (String address) { This. Address =address;} @Override PublicString toString () {return"Student [name=" + name + ", age=" + Age + ", address=" + address + "]";}}

Here's a way to convert the student object to JSON

 Public Static voidConvertobject () {Student stu=NewStudent (); Stu.setname ("JSON"); Stu.setage ("23"); Stu.setaddress ("Xicheng District, Beijing"); //1. Using JsonobjectJsonobject JSON =Jsonobject.fromobject (STU); //2. Using JsonarrayJsonarray array=Jsonarray.fromobject (STU); String Strjson=json.tostring (); String Strarray=array.tostring (); System.out.println ("Strjson:" +Strjson); System.out.println ("Strarray:" +Strarray); }

Jsonobject and Jsonarray methods print the results as follows:

strjson:{"Address": "Xicheng District, Beijing", "age": "All", "name": "JSON"}strarray:[{"address": "Xicheng, Beijing", "age": "All", "name": "JSON"}]
Jsonarray jsonarray=jsonarray.fromobject (ARRSTR); // get the first element of a JSON array Object o = jsonarray.get (0== (Student) Jsonobject.tobean (jsonobject,student.  Class);

JSON---Java object conversions

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.