An example of an interchange of JSON strings and Java objects in Java _java

Source: Internet
Author: User
Tags string format

In the development process, often need to exchange data with other systems, Data Interchange Format has XML, JSON and so on, JSON as a lightweight data format than XML more efficient, XML requires a lot of tags, which undoubtedly occupy the network traffic, JSON is doing a good job in this respect, Let's look at the format of JSON first,

JSON can have two formats, one in object format and the other in array objects,

{"Name": "JSON", "Address": "Xicheng District, Beijing", "age": String of 25}//json Object format

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

From the two formats above, you can see that the only difference between the object format and the array object format is the addition of [] to the object format. Then look at the specific structure, you can see that all are in the form of key-value pairs, the middle in the English state of the comma (,) separated.

This format is also popular when data is transmitted at the front and back end, 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 front-end use.

Let's get to the bottom of the list of the interactions between JSON and Java objects in Java.

To achieve the mutual transfer between JSON and Java objects, you need a third-party jar pack, which uses the Json-lib jar package, which is downloaded with the address: 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 packages of support, you can download from the Internet, here no longer post the download address.

Json-lib provides several classes that can complete this function, for example, Jsonobject, Jsonarray. From the name of the class can be seen jsonobject conversion should be the object format, and Jsonarray conversion should be the array object (that is, with [] form).

One, Java normal objects and JSON strings of the interchange

Java Object--"string"

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

Package com.cn.study.day3;
public class Student {
//name
private String name;
Ages
private String age;
Address
private String addresses;
Public String GetName () {return
name;
}
public void SetName (String name) {
this.name = name;
}
Public String Getage () {return age
;
}
public void Setage (String age) {
this.age = age;
}
Public String getaddress () {return address
;
}
public void setaddress (String address) {
this.address = address;
}
@Override public
String toString () {return
"Student [name=] + name +", age= + age +, address= "
+ addre SS + "]";
}
}

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

public static void Convertobject () {
Student stu=new Student ();
Stu.setname ("JSON");
Stu.setage ("the");
Stu.setaddress ("Xicheng District, Beijing");
1, using Jsonobject
jsonobject json = Jsonobject.fromobject (stu);
2, the use of Jsonarray
Jsonarray Array=jsonarray.fromobject (stu);
String strjson=json.tostring ();
String strarray=array.tostring ();
System.out.println ("Strjson:" +strjson);
System.out.println ("Strarray:" +strarray);
}

I've defined a student entity class and then used the Jsonobject and Jsonarray two ways to convert to a JSON string, which looks at the results of the print,

strjson:{"Address": "Beijing Xicheng District", "Age": "A", "name": "JSON"}
strarray:[{"Address": "Beijing Xicheng District", "Age": "A", "name": "JSON"}]

It can be seen from the results that both methods can convert Java objects into JSON strings, but 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.

First you need to define two strings in different formats, and you need to escape with the double quotes.

public static void Jsonstrtojava () {
//defines two different formats for string
objectstr= "{\ name\": \ "json\", \ "age\": \ "24\", \ " Address\ ":" "Beijing Xicheng District"} ";
String arraystr= "[{\ name\": \ "json\", "age\": \ "24\", "address\": \ "Beijing Xicheng District \"}];
1, the use of Jsonobject
jsonobject jsonobject=jsonobject.fromobject (OBJECTSTR);
Student stu= (Student) Jsonobject.tobean (Jsonobject, student.class);
2, the use of Jsonarray
Jsonarray jsonarray=jsonarray.fromobject (ARRAYSTR);
Gets the first element of the Jsonarray
Object 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, Peking City]
stu2:student [Name=json, age=24, address= Xicheng District, Peking City]

As you can see from the code above, using Jsonobject makes it easy to convert JSON-formatted strings into Java objects, but using Jsonarray is not so easy because it has a "[]" symbol, so after we've got the Jsonarray object, Take the first element that we need for a student variant and then use Jsonobject to easily get it.

Two, the list and JSON strings of the mutual transfer

list--"" JSON string

public static void Listtojson () {
Student stu=new Student ();
Stu.setname ("JSON");
Stu.setage ("the");
Stu.setaddress ("Haidian District, Beijing");
List<student> lists=new arraylist<student> ();
Lists.add (Stu);
1, the use of Jsonobject
//jsonobject listobject=jsonobject.fromobject (lists);
2, the use of Jsonarray
Jsonarray listarray=jsonarray.fromobject (lists);
System.out.println ("ListObject:" +listobject.tostring ());
System.out.println ("Listarray:" +listarray.tostring ());
}

I've got a note of how to use the Jsonobject, and we'll look at the results before the annotations,

Exception in thread "main" net.sf.json.JSONException: ' object ' was an array. Use Jsonarray instead
Tell me that there is an exception, by looking at the source found that in the use of the Fromobject method will be the first parameter type of judgment, here tells us that the incoming parameter is an array type, because the use of ArrayList, then look at the result of the annotation,

listarray:[{"Address": "Haidian District, Beijing", "Age": "A", "name": "JSON"}]
This result is normal.

JSON string--"" List

From the example above, we can see that the list object can only be converted into the array object format, so we look at the following string to the list transformation,

public static void Jsontolist () {
String arraystr= "[{\ name\": \ "json\", \ "age\": \ "24\", \ "address\": \ "Beijing Xicheng District \"}] " ;
Convert to List
list<student> list2= (list<student>) jsonarray.tolist (Jsonarray.fromobject (ARRAYSTR), Student.class);
for (Student stu:list2) {
System.out.println (stu);
}
Convert to Array
student[] ss = (student[]) Jsonarray.toarray (Jsonarray.fromobject (ARRAYSTR), student.class);
for (Student student:ss) {
System.out.println (Student);
}
}

Print results,

Student [Name=json, age=24, address= Xicheng District, Peking City]

Student [Name=json, age=24, address= Xicheng District, Peking City]

Because the string is formatted with a "[]" format, this option Jsonarray this object, which has a toarray, ToList method to use, which converts to an array in Java or to a list in Java, because there are entity classes to correspond, Therefore, when used, the generic type (Student.class) is specified, so that the transformed object can be obtained.

Three, map and JSON strings of the interchange

map--"" JSON string

public static void Maptojson () {
Student stu=new Student ();
Stu.setname ("JSON");
Stu.setage ("the");
Stu.setaddress ("Shanghai, China");
Map<string,student> map=new hashmap<string,student> ();
Map.put ("A", Stu);
1, Jsonobject
jsonobject mapobject=jsonobject.fromobject (map);
System.out.println ("MapObject" +mapobject.tostring ());
2, Jsonarray
jsonarray maparray=jsonarray.fromobject (map);
System.out.println ("Maparray:" +maparray.tostring ());
}

Print results,

Mapobject{"a": {"Address": "Shanghai, China", "Age": "N", "name": "JSON"}}
Maparray:[{"a": {"Address": "Shanghai, China", "Age": "N", "name": "JSON"}]

Two forms are printed above.

JSON string--"map"

The JSON string cannot be directly converted to a map object, and it takes a different way to get the value of the key in the map.

public static void Jsontomap () {
String strobject= "{\ first\": {\ "address\": \ "Shanghai, China", \ "age\": \ "23\", \ "name\": \ " Json\ "}}";
Jsonobject
jsonobject jsonobject=jsonobject.fromobject (strobject);
Map map=new HashMap ();
Map.put ("A", student.class);
Using the Tobean method, three parameters are required 
Mybean my= (Mybean) Jsonobject.tobean (Jsonobject, Mybean.class, map);
System.out.println (My.getfirst ());
}

Print results,

Student [Name=json, age=23, address=, Shanghai, China]

Here's the code for Mybean,

Package com.cn.study.day4;
Import Java.util.Map;
Import com.cn.study.day3.Student;
public class Mybean {
private Student;
Public Student GetFirst () {
return a public void Setfirst (Student i) {
this.first = i}

The Tobean () method is used to pass in three parameters, the first is the Jsonobject object, the second is Mybean.class, and the third is a map object. The Mybean can be known to have one of the properties in this class, and the type is student, to correspond to the key and value types in the map, that is, the type of the corresponding value of the type one in the corresponding key.

The above is a small set up to introduce the JSON string and Java objects to the conversion of examples to explain, I hope to help you!

Related Article

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.