Home > Java > javaTutorial > body text

How to convert java objects and json back and forth

WBOY
Release: 2023-05-03 10:55:06
forward
939 people have browsed it

1. The difference between JSON array and object

JSONArray is to convert the data into array form:

strArray:[{“address”:”北京市西城区”,”age”:”23”,”name”:”JSON”}]
Copy after login

When using it, you need to read the data in json in array mode, strArray[0].address;

JSONObject is to convert the data into a object form:

strJson:{“address”:”北京市西城区”,”age”:”23”,”name”:”JSON”}
Copy after login

When using, directly use the object method to read the data in json, strArray.address;

2. Convert the object to JSON

First convert the java object Convert to json object, after converting json object to json string

   //1、使用JSONObject
   JSONObject json = JSONObject.fromObject(stu);
   //2、使用JSONArray
   JSONArray array=JSONArray.fromObject(stu);   
   String strJson=json.toString();
   String strArray=array.toString();
Copy after login

3. Convert json string to java object

Also first convert json string to json object, and then convert the json object into a java object, as shown below.

JSONObject obj = new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象
Copy after login

Convert json object to java object

Person jb = (Person)JSONObject.toBean(obj,Person.class);//将建json对象转换为Person对象
Copy after login

The above is the detailed content of How to convert java objects and json back and forth. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template