The use of json construction and methods by JSON-lib package
The JSON-lib package (the two most critical classes are JSONObject and JSONArray) completes the construction of json and the use of some basic methods.
The difference between the two:
①The string constructed by JSONObject is in the form of key-value pairs (key:value), and multiple key-value pairs are connected with English commas;
②JSONArray The constructed string is in the form of an array ([array1, array2,...]).
Required package download link:
1. Use of JSONObject.
(1) Two construction methods for JSON strings:
① Use Java objects; ② Use Map collections.
Step 1: First create a new Java project and import dependency packages;
Step 2: Create two test classes:
Teacher.java
package com.snnu.json;import java.util.List;public class Teacher {private String name;private String sex;private int age;private List<Transport> myTool; public Teacher(){ } public Teacher(String name,String sex,int age,List<Transport> myTool){this.name = name;this.sex = sex;this.age = age;this.myTool = myTool; }public String getName() {return name; }public void setName(String name) {this.name = name; }public String getSex() {return sex; }public void setSex(String sex) {this.sex = sex; }public int getAge() {return age; }public void setAge(int age) {this.age = age; }public List<Transport> getMyTool() {return myTool; }public void setMyTool(List<Transport> myTool) {this.myTool = myTool; } }
Transport.java
package com.snnu.json;public class Transport { private String name;private float price; public Transport(){ } public Transport(String name,float price){this.name = name;this.price = price; } public String getName() {return name; }public void setName(String name) {this.name = name; }public float getPrice() {return price; }public void setPrice(float price) {this.price = price; } }
Step 3: Write the main method
Method 1:
package com.snnu.json;import java.util.ArrayList;import java.util.List;import net.sf.json.JSONObject;public class Demo_creajsonFromObject {// 利用java对象生成json字符串public JSONObject createJsonFromObject(Object object) {return JSONObject.fromObject(object); }public static void main(String[] args) {// TODO Auto-generated method stubDemo_creajsonFromObject demo = new Demo_creajsonFromObject(); Teacher t = new Teacher(); t.setName("张三"); t.setSex("男"); t.setAge(21); Transport bike = new Transport("自行车", 267); Transport motorcycle = new Transport("摩托车", 3267); Transport car = new Transport("小汽车", 100000); List<Transport> tools = new ArrayList<Transport>(); tools.add(bike); tools.add(motorcycle); tools.add(car); t.setMyTool(tools); JSONObject ob = demo.createJsonFromObject(t); System.out.println(ob); } }
Generate The json string is:
{ "age": 21, "myTool": [ { "name": "自行车", "price": 267 }, { "name": "摩托车", "price": 3267 }, { "name": "小汽车", "price": 100000 } ], "name": "张三", "sex": "男" }
Method 2:
package com.snnu.json;import java.util.HashMap;import java.util.Map;import net.sf.json.JSONObject;public class Demo_creajsonFromMap {//使用map集合生成json字符串public JSONObject createJsonFromMap(Map<String,String> map){ JSONObject jsob=new JSONObject(); jsob.putAll(map);return jsob; } public static void main(String[] args) {// TODO Auto-generated method stubDemo_creajsonFromMap demo=new Demo_creajsonFromMap(); Map<String,String> mmap=new HashMap<String,String>(); mmap.put("name", "张三"); mmap.put("sex", "男"); mmap.put("age", "21"); JSONObject ob=demo.createJsonFromMap(mmap); System.out.println(ob); } }
Generated json The string is:
{"sex": "男","name": "张三","age": "21"}
(2) Examples of three common methods of JSONObject.
package com.snnu.json;import java.util.ArrayList;import java.util.List;import net.sf.json.JSONObject;public class MethodTest {//put方法:在一个json中插入一个节点,若该节点已存在,则该节点的值将会被替换public JSONObject testPut(){ JSONObject jo1=new JSONObject(); jo1.put("a", "1"); jo1.put("b", "2"); jo1.put("c", "3"); Transport bike=new Transport("bike",200); jo1.put("d", bike); List<String> list=new ArrayList<String>(); list.add("one"); list.add("two"); list.add("three"); jo1.put("e", list); jo1.put("a", "100"); return jo1; } //accumulate方法:可以在同一个key下累积值,若key对应的value有值,则以数组形式累积;否则相当于put方法public JSONObject testAccumulate(){ JSONObject jo2=new JSONObject(); jo2.put("a", "1"); jo2.put("b", "2"); jo2.put("c", "3"); jo2.accumulate("c", "300"); Transport bike=new Transport("bike",200); jo2.accumulate("c", bike); List<String> list=new ArrayList<String>(); list.add("one"); list.add("two"); list.add("three"); jo2.accumulate("c", list); jo2.put("d", "4"); return jo2; } //与put方法基本一致public JSONObject testElement(){ JSONObject jo3=new JSONObject(); jo3.put("a", "1"); jo3.put("b", "2"); jo3.put("c", "3"); jo3.element("c", "300"); return jo3; } public static void main(String[] args) {// TODO Auto-generated method stubMethodTest test=new MethodTest(); System.out.println("JSONObject的put方法使用"+test.testPut()); System.out.println("JSONObject的accumulate方法使用"+test.testAccumulate()); System.out.println("JSONObject的element方法使用"+test.testElement()); } }
①The put method outputs the json string format and the result is:
{"a": "100","b": "2","c": "3","d": {"name": "bike","price": 200},"e": ["one","two","three"] }
②The accumulate method outputs the json string format The formatted result is:
{"a": "1","b": "2","c": ["3","300", {"name": "bike","price": 200}, ["one","two","three"] ],"d": "4"}
③The element method outputs the json string formatted result:
{"a": "1","b": "2","c": "300"}
2. Use of JSONArray
(1) Basic usage:
package com.snnu.json;import net.sf.json.JSONArray;import net.sf.json.JSONObject;public class demo_JsonArray { public JSONObject testJsonArray(){ JSONObject ob=new JSONObject(); JSONArray ja=new JSONArray(); ja.add("1"); ja.add("2"); ja.add("3"); ja.add("4"); ja.add("5"); ob.put("array", ja); return ob; } public static void main(String[] args) {// TODO Auto-generated method stubdemo_JsonArray djs=new demo_JsonArray(); System.out.println("JSONArray的使用:"+djs.testJsonArray()); } }
Format the output string:
{"array": ["1","2","3","4","5"] }
3. Comprehensive example
package com.snnu.json;import net.sf.json.JSONArray;import net.sf.json.JSONObject;public class demo_testJson { public JSONObject test(){ JSONObject jo=new JSONObject(); jo.put("name", "张三"); jo.put("sex","f"); jo.put("age",21); Transport bike=new Transport("bike",250); jo.put("extra", bike); Transport car=new Transport("car",10000); jo.accumulate("extra", car); Transport motor=new Transport("motor",3000); jo.accumulate("extra", motor); System.out.println(jo); //根据key值(为extra)取对应的valueString value=jo.getString("extra"); System.out.println(value); //将字符串转化为JSONArrayJSONArray jsar=JSONArray.fromObject(value); String str_2=String.valueOf(jsar.get(1)); System.out.println(str_2); //将字符串转化为JSONObjectJSONObject jsob=JSONObject.fromObject(str_2); System.out.println("名称:"+jsob.getString("name")); System.out.println("价钱:"+jsob.getString("price")); System.out.println("-------------------------------分界线-------------------------------------------"); return jo; }public static void main(String[] args) {// TODO Auto-generated method stubdemo_testJson dtj=new demo_testJson(); System.out.println("综合测试:"+dtj.test()); } }
The output result is:
{"name":"张三","sex":"f","age":21,"extra":[{"name":"bike","price":250},{"name":"car","price":10000},{"name":"motor","price":3000}]} [{"name":"bike","price":250},{"name":"car","price":10000},{"name":"motor","price":3000}] {"name":"car","price":10000} 名称:car 价钱:10000 -------------------------------分界线-------------------------------------------综合测试:{"name":"张三","sex":"f","age":21,"extra":[{"name":"bike","price":250},{"name":"car","price":10000},{"name":"motor","price":3000}]}
The above is the detailed content of The use of json construction and methods by JSON-lib package. 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



Detailed explanation of Oracle error 3114: How to solve it quickly, specific code examples are needed. During the development and management of Oracle database, we often encounter various errors, among which error 3114 is a relatively common problem. Error 3114 usually indicates a problem with the database connection, which may be caused by network failure, database service stop, or incorrect connection string settings. This article will explain in detail the cause of error 3114 and how to quickly solve this problem, and attach the specific code

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

[Analysis of the meaning and usage of midpoint in PHP] In PHP, midpoint (.) is a commonly used operator used to connect two strings or properties or methods of objects. In this article, we’ll take a deep dive into the meaning and usage of midpoints in PHP, illustrating them with concrete code examples. 1. Connect string midpoint operator. The most common usage in PHP is to connect two strings. By placing . between two strings, you can splice them together to form a new string. $string1=&qu

Analysis of new features of Win11: How to skip logging in to a Microsoft account. With the release of Windows 11, many users have found that it brings more convenience and new features. However, some users may not like having their system tied to a Microsoft account and wish to skip this step. This article will introduce some methods to help users skip logging in to a Microsoft account in Windows 11 and achieve a more private and autonomous experience. First, let’s understand why some users are reluctant to log in to their Microsoft account. On the one hand, some users worry that they

Due to space limitations, the following is a brief article: Apache2 is a commonly used web server software, and PHP is a widely used server-side scripting language. In the process of building a website, sometimes you encounter the problem that Apache2 cannot correctly parse the PHP file, causing the PHP code to fail to execute. This problem is usually caused by Apache2 not configuring the PHP module correctly, or the PHP module being incompatible with the version of Apache2. There are generally two ways to solve this problem, one is

Introduction XML (Extensible Markup Language) is a popular format for storing and transmitting data. Parsing XML in Java is a necessary task for many applications, from data exchange to document processing. To parse XML efficiently, developers can use various Java libraries. This article will compare some of the most popular XML parsing libraries, focusing on their features, functionality, and performance to help developers make an informed choice. DOM (Document Object Model) parsing library JavaXMLDOMAPI: a standard DOM implementation provided by Oracle. It provides an object model that allows developers to access and manipulate XML documents. DocumentBuilderFactoryfactory=D

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.
