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

Detailed explanation of how to use JSONObject_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:24:591738browse

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.

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":"张三"}

xml

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

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);
 }

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());
 }

 

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);
 }

 

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());
 }

 

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());
 }

 

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);
 }

 

完整的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();
 }
 }

完整的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;
 }
 }

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" 

解决方案:导入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" 

解决方案:导入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" 

解决方案:导入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" 

解决方案:导入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" 

解决方案:导入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) 

解决方案:导入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:
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