Json-lib one of the Java and JSON string conversions

Source: Internet
Author: User
Tags string format

This article mainly introduces in Java, JSON string and Java Object Conversion example of each other, very good, with reference value, the need for friends can refer to.

In the development process, often need to exchange data with other systems, the format of data exchange is XML, JSON, etc., JSON as a lightweight data format than XML efficiency, XML needs a lot of tags, which undoubtedly occupy the network traffic, JSON is doing well in this respect, Let's look at the JSON format below,

JSON can be in two formats, one in object format and the other as an array object.

{"Name": "JSON", "Address": "Xicheng District, Beijing", "age": 25}//json Object-formatted string

[{"Name": "JSON", "Address": "Xicheng District, Beijing", "age": 25}]//data Object Format

From the above two formats can be seen in the object format and the format of the array object is the only difference is the object format based on the addition of [], and then to see the specific structure, you can see the form of key-value pairs, the middle of the English state of the comma (,) separated.

This format is also popular when transmitting data at the front and back ends, and the backend returns a JSON-formatted string, and the foreground uses the Json.parse () method in JS to parse the JSON string into a JSON object and then traverse it for use by the front end.

Let's go to the bottom and introduce the interaction between JSON and Java objects in Java.

To implement the interaction between JSON and Java objects, you need a third-party jar package, which uses the Json-lib jar package: https://sourceforge.net/projects/json-lib/, Json-lib need Commons-beanutils-1.8.0.jar, Commons-collections-3.2.1.jar, Commons-lang-2.5.jar, Commons-logging-1.1.1.jar, Ezmorph-1.0.6.jar Five packs of support, you can download from the Internet, no longer posted here.

Json-lib provides several classes that can accomplish this function, for example, Jsonobject, Jsonarray. From the name of the class you can see that the Jsonobject transformation should be the object format, while the Jsonarray conversion should be the array object (i.e., with [] form).

One, Java common Object and JSON string of the mutual transfer

Java Object--"string"

Java generic object refers to a Java Bean in Java, that is, an entity class, such as,

 PackageCom.cn.study.day3; 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 + "]";}}

Above is one of my ordinary Java entity classes, see how json-lib it into a string form,

PublicStaticvoid Convertobject () {Student stu= new Student (); Stu.setname ("JSON" // 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);}        

I defined a student entity class, and then I used the Jsonobject and Jsonarray two ways to convert to a JSON string, see the results of the printing,

strjson:{"Address": "Xicheng District, Beijing", "age": "All", "name": "JSON"}
strarray:[{"Address": "Xicheng District, Beijing", "age": "All", "name": "JSON"}]

It can be seen from the results that both methods can convert Java objects to JSON strings, except that the transformed structure is different.

JSON string--"Java object

It shows how to convert a Java object into a JSON string and see how to convert the JSON string format to a Java object.

You first need to define two different formats of strings, you need to use \ to escape double quotes,

 Public Static voidJsonstrtojava () {//define two strings in different formatsString objectstr= "{\" name\ ": \" json\ ", \" age\ ": \" 24\ ", \" address\ ": \" Beijing Xicheng District \ "}"; String Arraystr= "[{\" name\ ": \" json\ ", \" age\ ": \" 24\ ", \" address\ ": \" Xicheng District, Beijing, "}]";//1. Using JsonobjectJsonobject jsonobject=Jsonobject.fromobject (OBJECTSTR); Student Stu= (Student) Jsonobject.tobean (Jsonobject, Student.class);//2. Using JsonarrayJsonarray jsonarray=Jsonarray.fromobject (ARRAYSTR);//get the first element of a JsonarrayObject O=jsonarray.get (0); Jsonobject JsonObject2=Jsonobject.fromobject (o); Student STU2= (Student) Jsonobject.tobean (JsonObject2, Student.class); System.out.println ("Stu:" +Stu); System.out.println ("STU2:" +stu2);}

Printing results are:

stu:student [Name=json, age=24, address=, Xicheng District, Beijing]
stu2:student [Name=json, age=24, address=, Xicheng District, Beijing]

As you can see from the code above, using Jsonobject can easily convert a JSON-formatted string into a Java object, but using Jsonarray is not as easy as it has a "[]" symbol, so after we get the Jsonarray object here, Take its first element, which is a student transformation we need, and then use Jsonobject to easily get it.

Json-lib one of the Java and JSON string 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.