Introduction to several forms of Javabean and JSON conversion
The following editor will bring you an article that discusses several forms of JSON and Javabean conversion in detail. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
JSON format data transfer is one of the most commonly used methods. The following lists several commonly used forms and conversions with Javabeans:
String json1="{'name':'zhangsan','age':23,'interests':[{'interest':'篮球','colors':['绿色','黄色']},{'interest':'足球','colors':['红色','蓝色']}]}"; String json2="[{'name':'zhangsan'},{'name':'lisi'},{'name':'王五'}]"; String json3="{'1':{'name':'zhangsan'},'3':{'name':'lisi'},'4':{'name':'wangwu'}}";//map String json4="{'name':'zhangsan','age':23}";
First of all, the transformation here relies on two JAR packages
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.json/json --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20170516</version> </dependency>
Secondly, the encapsulated Javabean code is as follows
import java.util.List; public class UserBean { private String name; private Integer age; private List<InterestBean> interests; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public List<InterestBean> getInterests() { return interests; } public void setInterests(List<InterestBean> interests) { this.interests = interests; } class InterestBean{ private String interest; private List<String> colors; public String getInterest() { return interest; } public void setInterest(String interest) { this.interest = interest; } public List<String> getColors() { return colors; } public void setColors(List<String> colors) { this.colors = colors; } } }
1. JSON parsing in ordinary json4 format:
public void testParseJson(){ JSONObject jsonObj = new JSONObject(json4); String name = jsonObj.getString("name"); int age = jsonObj.getInt("age"); System.out.println(name); System.out.println(age); UserBean user = new UserBean(); user.setAge(age); user.setName(name); }
2. JSON parsing in array form and GSON parsing:
public void testJsonArray(){ JSONArray jsonArray = new JSONArray(json2); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObj = jsonArray.getJSONObject(i); String name = jsonObj.getString("name"); System.out.println(name); } }
/** * 解析json数组 */ public void testParseListJson(){ Gson gson = new Gson(); Type type = new TypeToken<List<UserBean>>(){}.getType(); List<UserBean> users = gson.fromJson(json2, type); for(UserBean user:users){ System.out.println(user.getName()); } }
3. JSON and GSON parsing in embedded JSON form:
/** * 内嵌JSON解析 */ public void testParseJson1(){ JSONObject rootJson = new JSONObject(json1); JSONArray jsonInterestArray = rootJson.getJSONArray("interests"); for (int i = 0; i < jsonInterestArray.length(); i++) { JSONObject interestJsonObj = jsonInterestArray.getJSONObject(i); String interest = interestJsonObj.getString("interest"); System.out.println(interest); Object obj = interestJsonObj.get("colors"); System.out.println(obj); } }
/** * 内嵌GSON解析 */ public void testSimpleJson(){ Gson gson = new Gson(); UserBean user = gson.fromJson(json1, UserBean.class); System.out.println(user.getName()); System.out.println(user.getAge()); System.out.println(user.getInterests().size()); List<InterestBean> list = user.getInterests(); for(InterestBean bean:list) { System.out.println(bean.getInterest()); List<String> colors = bean.getColors(); for(String color:colors){ System.out.println(color); } } }
4. GSON parsing of JSON in Map form:
/** * 解析一个map类型的json */ public void testParseMapJson(){ Gson gson = new Gson(); Type type = new TypeToken<Map<String,UserBean>>(){}.getType(); Map<String,UserBean> map = gson.fromJson(json3, type); Set<String> keys = map.keySet(); for(String key:keys){ UserBean bean = map.get(key); System.out.println(key); System.out.println(bean.getName()); } }
5. Encapsulate a JavaBean object into JSON format
/** * 将一个JavaBean对象封装成JSON格式 */ public String testJavaBean2Json(){ UserBean userBean = new UserBean(); userBean.setName("zhangsan"); userBean.setAge(33); List<InterestBean> list = new ArrayList<InterestBean>(); InterestBean bean1 = new UserBean().new InterestBean(); bean1.setInterest("篮球1"); InterestBean bean2 = new UserBean().new InterestBean(); bean2.setInterest("篮球2"); list.add(bean1); list.add(bean2); userBean.setInterests(list); //将User Bean转换成Json Gson gson = new Gson(); String jsonStr = gson.toJson(userBean); System.out.println(jsonStr); return jsonStr; } }
The above is the detailed content of Introduction to several forms of Javabean and JSON conversion. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.
