The conversion between Java data and JSON data

Source: Internet
Author: User

Java Data format:

Class test{

private String name;

Private String sex;

Private String Brith;

}

JSON data format:

{"Name": "Keke", "Sex": "Male", "Brith": "0301"}

One, the Java data is converted to JSON data:

1. Object Conversion

test test = new test ();

Test.setname ("Keke");

Test.setsex ("male");

Test.setbrith ("0301");

Jsonobject JSON = jsonobject.fromobject (test); //Convert a Java object to a JSON object   

String strText = json.tostring (); //Convert a JSON object to a string  

2. Direct conversion

Jsonobject opmsg = new Jsonobject ();
Opmsg.put ("name", "Keke");
Opmsg.put ("Sex", "male");
Opmsg.put ("Brith", "0301");
String StrText = opmsg.tostring ();

Second, the JSON data is converted to Java

1. Separate settings

Sonobject jsonobject = Jsonobject.fromobject (StrText);

Test test = new test ();

Test.setname (jsonobject.getstring ("name"));

test.setsex (jsonobject.getstring ("Sex"));

Test.setbrith (Jsonobject.getint ("age"));

2. Direct conversion

Jsonobject obj = new jsonobject (). Fromobject (StrText); //Convert a JSON string to a JSON object   

Test test = (test) Jsonobject.tobean (obj,test.class); //Convert the built JSON object to the test object

The required jar package http://pan.baidu.com/share/link?shareid=398380&uk=3457081238 in the project

Reference Blog http://blog.csdn.net/gchb9527/article/details/8688279

The conversion between Java data and JSON data

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.