Home Web Front-end JS Tutorial Detailed explanation of how to use JSONObject_javascript skills

Detailed explanation of how to use JSONObject_javascript skills

May 16, 2016 pm 03:24 PM
jsonobject

1.JSONObject introduction

The JSONObject-lib package is a package for converting beans, collections, maps, java arrays, and xml to JSON.

2. Download the jar package

http://files.cnblogs.com/java-pan/lib.rar

Provides 6 other jar packages that are dependent on JSONObject's jar, a total of 7 jar files

Note: Because the version used in the project at work is 1.1, which corresponds to the jdk1.3 version, this blog is based on the 1.1 version.

The javadoc download path corresponding to this version is as follows: http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-1.1/

The latest version is 2.4. The download address for other versions is http://sourceforge.net/projects/json-lib/files/json-lib/

3. Project environment:

system: WIN7 myeclipse: 6.5 tomcat: 5.0 JDK: both development environment and compilation use 1.5

The project structure is as follows:

Note: The files used this time are only the JSONObject_1_3 class and note.txt under the json package in the project directory

4.class&method API based on 1.1

Make the following agreements:

1. Introducing the API based on JSONObject 1.1

2. Only introduce commonly used classes and methods

3. No longer introduced. This version is no longer recommended.

4. The classes and methods introduced mainly focus on the ones used in this blog

JSONObject:A JSONObject is an unordered collection of name/value pairs.
Copy after login

is a final class, inherits Object and implements the JSON interface

The construction method is as follows:

JSONObject(); Create an empty JSONObject object

JSONObject(boolean isNull); Create a JSONObject object whether it is empty

The common method is as follows:

fromBean(Object bean); Static method, creates a JSONObject object through a pojo object

fromJSONObject(JSONObject object); Static method, constructs a JSONObject object through another JSONObject object

fromJSONString(JSONString string); Static method, creates a JSONObject object through a JSONString

toString(); Convert JSONObject object to json format string

iterator(); returns an Iterator object to traverse elements

Next are some put/get methods. The ordinary get methods and pot methods need to be emphasized. The API is described like this:

A get method returns a value if one can be found, and throws an exception if one cannot be found. An opt method returns a default value instead of throwing an exception, and so is useful for obtaining optional values.

JSONArray:A JSONArray is an ordered sequence of values.

is a final class, inherits Object and implements the JSON interface

The construction method is as follows:

JSONArray(); constructs an empty JSONArray object

The common method is as follows:

fromArray(Object[] array); Static method, creates a JSONArray object through a java array

fromCollection(Collection collection); Static method, creates a JSONArray object through the collection object

fromString(String string); static method, constructs a JSONArray object from a json format string

toString(); Convert JSONArray object to json format string

iterator(); returns an Iterator object to traverse elements

The next step is also the put/get method...

XMLSerializer:Utility class for transforming JSON to XML an back.

A class that inherits from Object

The construction method is as follows:

XMLSerializer(); Create an XMLSerializer object

The common method is as follows:

setRootName(String rootName); Set the root element name of the converted xml

setTypeHintsEnabled(boolean typeHintsEnabled); Set whether each element displays the type attribute

write(JSON json); Convert json object to xml. The default character encoding is UTF-8,

If you need to set the encoding, you can use write(JSON json, String encoding)

5. A simple example for each column of XML and JSON strings

JSON:

{"password":"123456","username":"张三"}
Copy after login

xml

<&#63;xml version="1.0" encoding="UTF-8"&#63;> 
<user_info>
<password>123456</password>
<username>张三</username>
</user_info>
Copy after login

start

Create a new web project with the project name JS and import the following 7 jar packages. The files are downloaded from the path in the previous preparations.

Note: You don’t need to create a new web project. Ordinary java projects can also complete the operations in this article. As for why I need to import the other 6 packages besides the json package, I will post the note.txt at the end so that you can know at a glance.

question1: How to process the json format string received from the frontend in the background?

 public static void jsonToJAVA() {
 System.out.println("json字符串转java代码");
 String jsonStr = "{\"password\":\"\",\"username\":\"张三\"}";
 JSONObject jsonObj = JSONObject.fromString(jsonStr);
 String username = jsonObj.getString("username");
 String password = jsonObj.optString("password");
 System.out.println("json--->java\n username=" + username
 + "\t password=" + password);
 }
Copy after login

question2:后台是怎么拼装json格式的字符串?

 public static void javaToJSON() {
 System.out.println("java代码封装为json字符串");
 JSONObject jsonObj = new JSONObject();
 jsonObj.put("username", "张三");
 jsonObj.put("password", "");
 System.out.println("java--->json \n" + jsonObj.toString());
 }
Copy after login

question3:json格式的字符串怎么转换为xml格式的字符串?

 public static void jsonToXML() {
 System.out.println("json字符串转xml字符串");
 String jsonStr = "{\"password\":\"\",\"username\":\"张三\"}";
 JSONObject json = JSONObject.fromString(jsonStr);
 XMLSerializer xmlSerializer = new XMLSerializer();
 xmlSerializer.setRootName("user_info");
 xmlSerializer.setTypeHintsEnabled(false);
 String xml = xmlSerializer.write(json);
 System.out.println("json--->xml \n" + xml);
 }
Copy after login

question4:xml格式的字符串怎么转换为json格式的字符串?

public static void xmlToJSON(){
 System.out.println("xml字符串转json字符串");
 String xml = "<&#63;xml version=\".\" encoding=\"UTF-\"&#63;><user_info><password></password><username>张三</username></user_info>";
 JSON json=XMLSerializer.read(xml);
 System.out.println("xml--->json \n"+json.toString());
 }
Copy after login

question5:javabean怎么转换为json字符串?

public static void javaBeanToJSON() {
 System.out.println("javabean转json字符串");
 UserInfo userInfo = new UserInfo();
 userInfo.setUsername("张三");
 userInfo.setPassword("");
 JSONObject json = JSONObject.fromBean(userInfo);
 System.out.println("javabean--->json \n" + json.toString());
 }
Copy after login

question6:javabean怎么转换为xml字符串?

public static void javaBeanToXML() {
 System.out.println("javabean转xml字符串");
 UserInfo userInfo = new UserInfo();
 userInfo.setUsername("张三");
 userInfo.setPassword("");
 JSONObject json = JSONObject.fromBean(userInfo);
 XMLSerializer xmlSerializer = new XMLSerializer();
 String xml = xmlSerializer.write(json, "UTF-");
 System.out.println("javabean--->xml \n" + xml);
 }
Copy after login

完整的JSONObject_1_3.java代码如下:

JSONObject_1_3
 package json;
 import net.sf.json.JSON;
 import net.sf.json.JSONObject;
 import net.sf.json.xml.XMLSerializer;
 public class JSONObject__ {
 public static void javaToJSON() {
 System.out.println("java代码封装为json字符串");
 JSONObject jsonObj = new JSONObject();
 jsonObj.put("username", "张三");
 jsonObj.put("password", "");
 System.out.println("java--->json \n" + jsonObj.toString());
 }
 public static void jsonToJAVA() {
 System.out.println("json字符串转java代码");
 String jsonStr = "{\"password\":\"\",\"username\":\"张三\"}";
 JSONObject jsonObj = JSONObject.fromString(jsonStr);
 String username = jsonObj.getString("username");
 String password = jsonObj.optString("password");
 System.out.println("json--->java\n username=" + username
 + "\t password=" + password);
 }
 public static void jsonToXML() {
 System.out.println("json字符串转xml字符串");
 String jsonStr = "{\"password\":\"\",\"username\":\"张三\"}";
 JSONObject json = JSONObject.fromString(jsonStr);
 XMLSerializer xmlSerializer = new XMLSerializer();
 xmlSerializer.setRootName("user_info");
 xmlSerializer.setTypeHintsEnabled(false);
 String xml = xmlSerializer.write(json);
 System.out.println("json--->xml \n" + xml);
 }
 public static void javaBeanToJSON() {
 System.out.println("javabean转json字符串");
 UserInfo userInfo = new UserInfo();
 userInfo.setUsername("张三");
 userInfo.setPassword("");
 JSONObject json = JSONObject.fromBean(userInfo);
 System.out.println("javabean--->json \n" + json.toString());
 }
 public static void javaBeanToXML() {
 System.out.println("javabean转xml字符串");
 UserInfo userInfo = new UserInfo();
 userInfo.setUsername("张三");
 userInfo.setPassword("");
 JSONObject json = JSONObject.fromBean(userInfo);
 XMLSerializer xmlSerializer = new XMLSerializer();
 String xml = xmlSerializer.write(json, "UTF-");
 System.out.println("javabean--->xml \n" + xml);
 }
 public static void xmlToJSON(){
 System.out.println("xml字符串转json字符串");
 String xml = "<?xml version=\".\" encoding=\"UTF-\"?>张三";
 JSON json=XMLSerializer.read(xml);
 System.out.println("xml--->json \n"+json.toString());
 }
 public static void main(String args[]) {
 // javaToJSON();
 // jsonToJAVA();
 // jsonToXML();
 // javaBeanToJSON();
 // javaBeanToXML();
 xmlToJSON();
 }
 }
Copy after login

完整的UserInfo.java代码如下:

UserInfo
 package json;
 public class UserInfo {
 public String username;
 public String password;
 public String getUsername() {
 return username;
 }
 public void setUsername(String username) {
 this.username = username;
 }
 public String getPassword() {
 return password;
 }
 public void setPassword(String password) {
 this.password = password;
 }
 }
Copy after login

result

代码和运行结果都已经贴在每个问题的后面,运行时直接用main方法分别对每个方法运行即可看到测试效果。

note.txt是报的对应的错误及解决方法,也从另一个方面说明为什么需要导入前面提到的jar包;

note.txt文件内容如下:

java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException 
at java.lang.ClassLoader.defineClass0(Native Method) 
at java.lang.ClassLoader.defineClass(ClassLoader.java:537) 
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123) 
at java.net.URLClassLoader.defineClass(URLClassLoader.java:251) 
at java.net.URLClassLoader.access$100(URLClassLoader.java:55) 
at java.net.URLClassLoader$1.run(URLClassLoader.java:194) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.net.URLClassLoader.findClass(URLClassLoader.java:187) 
at java.lang.ClassLoader.loadClass(ClassLoader.java:289) 
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274) 
at java.lang.ClassLoader.loadClass(ClassLoader.java:235) 
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302) 
at generate.TestJSONObject.main(TestJSONObject.java:40) 
Exception in thread "main" 
Copy after login

解决方案:导入commons-lang-2.1.jar

java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory 
at net.sf.json.JSONObject.<clinit>(JSONObject.java:125) 
at generate.TestJSONObject.main(TestJSONObject.java:40) 
Exception in thread "main" 
Copy after login

解决方案:导入commons-logging.jar

java.lang.NoClassDefFoundError: org/apache/commons/beanutils/DynaBean 
at net.sf.json.JSONObject.set(JSONObject.java:2164) 
at net.sf.json.JSONObject.put(JSONObject.java:1853) 
at net.sf.json.JSONObject.put(JSONObject.java:1806) 
at generate.TestJSONObject.main(TestJSONObject.java:41) 
Exception in thread "main" 
Copy after login

解决方案:导入commons-beanutils.jar

java.lang.NoClassDefFoundError: net/sf/ezmorph/MorpherRegistry 
at net.sf.json.util.JSONUtils.<clinit>(JSONUtils.java:65) 
at net.sf.json.JSONObject.set(JSONObject.java:2164) 
at net.sf.json.JSONObject.put(JSONObject.java:1853) 
at net.sf.json.JSONObject.put(JSONObject.java:1806) 
at generate.TestJSONObject.main(TestJSONObject.java:41) 
Exception in thread "main" 

Copy after login

解决方案:导入ezmorph-1.0.2.jar

java.lang.NoClassDefFoundError: org/apache/commons/collections/FastHashMap 
at org.apache.commons.beanutils.PropertyUtils.<clinit>(PropertyUtils.java:208) 
at net.sf.json.JSONObject.fromBean(JSONObject.java:190) 
at net.sf.json.JSONObject.fromObject(JSONObject.java:437) 
at net.sf.json.JSONObject.set(JSONObject.java:2196) 
at net.sf.json.JSONObject.put(JSONObject.java:1853) 
at net.sf.json.JSONObject.put(JSONObject.java:1806) 
at generate.TestJSONObject.main(TestJSONObject.java:41) 
Exception in thread "main" 
Copy after login

解决方案:导入commons-collections-3.0.jar

Exception in thread "main" java.lang.NoClassDefFoundError: nu/xom/Serializer 
at generate.TestJSONObject.jsonToXML(TestJSONObject.java:88) 
at generate.TestJSONObject.main(TestJSONObject.java:96) 
Copy after login

解决方案:导入xom-1.0d10.jar

几点说明:

1.注意UserInfo类的修饰符,用public修饰,变量username和password也用public修饰,最好单独的写一个类,这里就不贴出来了

2.以上json字符串和xml字符串都是最简单的形式,实际开发中json字符串和xml格式比这个复杂的多,

处理复杂的json字符串,可以封装写一个类继承HashMap,然后重写其put和get方法,以支持对类型为A[0].B及A.B的键值的读取和指定

3.以上6中情况在实际开发中可能有些不存在或不常用

存在的问题:

1.使用XMLSerializer的write方法生成的xml字符串的中文乱码问题

2.question4中的红色的log日志问题

以上内容是小编给大家介绍的JSONObject使用方法详解,希望大家喜欢。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles