JSON strings are transferred to and from Java objects

Source: Internet
Author: User
Tags string format

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,

?
1234567891011121314151617181920212223242526272829303132 package com.cn.study.day3;public class Student {//姓名private String name;//年龄private String age;//住址private String address;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;}@Overridepublic String 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,

?
1234567891011121314 public static void convertObject() {Student stu=new Student();stu.setName("JSON");stu.setAge("23");stu.setAddress("北京市西城区");//1、使用JSONObjectJSONObject json = JSONObject.fromObject(stu);//2、使用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,

?
12345678910111213141516 public static void jsonStrToJava(){//定义两种不同格式的字符串String objectStr="{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}";String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}]";//1、使用JSONObjectJSONObject jsonObject=JSONObject.fromObject(objectStr);Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);//2、使用JSONArrayJSONArray jsonArray=JSONArray.fromObject(arrayStr);//获得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, 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.

Second, the list and JSON string of the mutual transfer

list--"JSON string

?
1234567891011121314 public static void listToJSON(){Student stu=new Student();stu.setName("JSON");stu.setAge("23");stu.setAddress("北京市海淀区");List<Student> lists=new ArrayList<Student>();lists.add(stu);//1、使用JSONObject//JSONObject listObject=JSONObject.fromObject(lists);//2、使用JSONArrayJSONArray listArray=JSONArray.fromObject(lists);//System.out.println("listObject:"+listObject.toString());System.out.println("listArray:"+listArray.toString());}

I've jsonobject the way I used it, and we'll look at the results before the comments,

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 code discovery, when using the Fromobject method will be the parameter type of judgment, here tells us that the passed parameter is an array type, because the use of the ArrayList, then see, the result after the comment,

listarray:[{"Address": "Haidian District, Beijing", "age": "All", "name": "JSON"}]
So the result is normal.

JSON string-"list"

From the above example, we can see that the list object can only be converted to the format of the array object, then we look at the following string to list conversion,

?
12345678910111213 public static void jsonToList(){String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}]";//转化为listList<Student> list2=(List<Student>)JSONArray.toList(JSONArray.fromObject(arrayStr), Student.class);for (Student stu : list2) {System.out.println(stu);}//转化为数组Student[] ss =(Student[])JSONArray.toArray(JSONArray.fromObject(arrayStr),Student.class);for (Student student : ss) {System.out.println(student);}}

Printing results,

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

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

Because the format of the string is a format with "[]", so here jsonarray this object, it has a toarray, ToList method is available, the former is converted to an array in Java, or into a list in Java, because there are entity classes to correspond, Therefore, the type of the generic (Student.class) is specified when it is used, so that the converted object can be obtained.

Third, map and JSON string cross-transfer

map--"JSON string

?
1234567891011121314 public static void mapToJSON(){Student stu=new Student();stu.setName("JSON");stu.setAge("23");stu.setAddress("中国上海");Map<String,Student> map=new HashMap<String,Student>();map.put("first", stu);//1、JSONObjectJSONObject mapObject=JSONObject.fromObject(map);System.out.println("mapObject"+mapObject.toString());//2、JSONArrayJSONArray mapArray=JSONArray.fromObject(map);System.out.println("mapArray:"+mapArray.toString());}

Printing results,

mapobject{"First": {"Address": "Shanghai, China", "age": "+", "name": "JSON"}}
maparray:[{"First": {"Address": "Shanghai, China", "age": "+", "name": "JSON"}]

There are two forms printed on it.

JSON string-"map"

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

?
12345678910 public static void jsonToMap(){String strObject="{\"first\":{\"address\":\"中国上海\",\"age\":\"23\",\"name\":\"JSON\"}}";//JSONObjectJSONObject jsonObject=JSONObject.fromObject(strObject);Map map=new HashMap();map.put("first", Student.class);//使用了toBean方法,需要三个参数 MyBean my=(MyBean)JSONObject.toBean(jsonObject, MyBean.class, map);System.out.println(my.getFirst());}

Printing results,

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

Here is the code for Mybean,

?
123456789101112 package com.cn.study.day4;import java.util.Map;import com.cn.study.day3.Student;public class MyBean {private Student first;public Student getFirst() {return first;}public void setFirst(Student first) {this.first = first;}}

Using the Tobean () method is passed three parameters, the first is the Jsonobject object, the second is Mybean.class, and the third is a map object. The Mybean can be used to know that there is a first attribute in this class, and its type is student, which corresponds to the key and value type in map, that is, first corresponds to the type of the key first type corresponding to the value.

JSON strings are transferred to and from Java objects

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.