Use of json-IT software learning

Understanding of JSON and the mutual conversion of JSON data
Json and Jsonlib use
What is Json
JSON (JvaScript Object Notation) (Official website: http://www.json.org/ ) is a lightweight data exchange format. Easy to read and write. It is also easy for machine analysis and generation. It is based on a subset of JavaScript Programming Language, Standard ECMA-262 3rd Edition-December 1999. JSON uses a completely language-independent text format, but also uses habits similar to the C language family (including C, C ++, C #, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language.

Two structures of JSON
1. A collection of name / value pairs. In different languages, it is understood as an object, record, struct, dictionary, hash table, keyed list, or associative array array). In the Java language, we can understand it as HashMap.

The object is an unordered collection of "name / value" pairs. An object starts with "{" (left bracket) and ends with "}" (right bracket). Each "name" is followed by a ":" (colon); "" name / value "pairs are separated by", "(comma).

Example: var json = {"name": "Jack", "age": 90, "Marray": true};

  1. An ordered list of values. In most languages, it is understood as an array (Array or List).

An array is an ordered collection of values. An array starts with "[" (left bracket) and ends with "]" (right bracket). Use "," (comma) to separate values.

Example: var json = ["Jack", "Rose", "Tom", 89, true, false];

Json-lib
Json-lib is a Java class library (official website: http://json-lib.sourceforge.net/ ) that can implement the following functions:

Convert javabeans, maps, collections, java arrays and XML into json format data
Convert json format data into
jar packages required by javabeans object Json-lib

commons-beanutils-1.8.3.jar
commons-collections-3.2.1.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar

—> Click to download jar package

Use of Json-lib

  1. Parse Array into Json string. Use JSONArray to parse the Array type:

package cn.sunzn.json;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.sf.json.JSONArray;

public class JsonLib {
public static void main(String[] args) {
/**
* 将 Array 解析成 Json 串
*/
String[] str = { “Jack”, “Tom”, “90”, “true” };
JSONArray json = JSONArray.fromObject(str);
System.err.println(json);

   /**
    * 对像数组,注意数字和布而值
    */
   Object[] o = { "北京", "上海", 89, true, 90.87 };
   json = JSONArray.fromObject(o);
   System.err.println(json);

   /**
    * 使用集合类
    */
   List<String> list = new ArrayList<String>();
   list.add("Jack");
   list.add("Rose");
   json = JSONArray.fromObject(list);
   System.err.println(json);

   /**
    * 使用 set 集
    */
   Set<Object> set = new HashSet<Object>();
   set.add("Hello");
   set.add(true);
   set.add(99);
   json = JSONArray.fromObject(set);
   System.err.println(json);

}
}

The results are as follows:

["Jack", "Tom", "90", "true"]
["Beijing", "Shanghai", 89, true, 90.87]
["Jack", "Rose"]
[99, true, "Hello"]
2. Parse the JavaBean / Map into a JSON string. Use JSONObject to parse:

package cn.sunzn.json;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

public class JsonLib {
@SuppressWarnings(“static-access”)
public static void main(String[] args) {
/**
* 解析 HashMap
*/
Map<String, Object> map = new HashMap<String, Object>();
map.put(“name”, “Tom”);
map.put(“age”, 33);
JSONObject jsonObject = JSONObject.fromObject(map);
System.out.println(jsonObject);

   /**
    * 解析 JavaBean
    */
   Person person = new Person("A001", "Jack");
   jsonObject = jsonObject.fromObject(person);
   System.out.println(jsonObject);

   /**
    * 解析嵌套的对象
    */
   map.put("person", person);
   jsonObject = jsonObject.fromObject(map);
   System.out.println(jsonObject);

}
}

The results are as follows:

{"Age": 33, "name": "Tom"}
{"id": "A001", "name": "Jack"}
{"person": {"id": "A001", "name": "Jack"}, "age": 33, "name": "Tom"}
3. Use JsonConfig to consider attributes: applicable to JavaBean / Map

package cn.sunzn.json;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class JsonLib {
public static void main (String [] args) {
JsonConfig config = new JsonConfig ();
config.setExcludes (new String [] {“name”}); // Specify which attributes
Person person is not included in the conversion = new Person (“A001”, “Jack”);
JSONObject jsonObject = JSONObject.fromObject (person, config); //
Pass in the previous configuration object during conversion System.out.println (jsonObject);
}
}

The running result is as follows. In the running result, we can see that the name attribute is filtered out:

{“Id”: “A001”}
4. Convert Json string to Array:

package cn.sunzn.json;

import java.util.Arrays;
import net.sf.json.JSONArray;

public class JsonLib {
public static void main(String[] args) {
JSONArray jsonArray = JSONArray.fromObject("[89,90,99]");
Object array = JSONArray.toArray(jsonArray);
System.out.println(array);
System.out.println(Arrays.asList((Object[]) array));
}
}

The results are as follows:

[Ljava.lang.Object; @ 1e5003f6
[89, 90, 99]
5. Convert Json string to JavaBean / Map:

package cn.sunzn.json;

import java.util.Map;

import net.sf.json.JSONObject;

public class JsonLib {
@SuppressWarnings(“unchecked”)
public static void main(String[] args) {
/**
* 将 Json 形式的字符串转换为 Map
*/
String str = “{“name”:“Tom”,“age”:90}”;
JSONObject jsonObject = JSONObject.fromObject(str);
Map<String, Object> map = (Map<String, Object>) JSONObject.toBean(jsonObject, Map.class);
System.out.println(map);

   /**
    * 将 Json 形式的字符串转换为 JavaBean
    */
   str = "{\"id\":\"A001\",\"name\":\"Jack\"}";
   jsonObject = JSONObject.fromObject(str);
   System.out.println(jsonObject);
   Person person = (Person) JSONObject.toBean(jsonObject, Person.class);
   System.out.println(person);

}
}

The results are as follows:

{age = 90, name = Tom}
Person [id = A001, name = Jack]
When converting a Json-style string to JavaBean, you need to pay attention to the fact that there must be no parameter constructor in JavaBean, otherwise it will report as follows. Method error:

Exception in thread “main” net.sf.json.JSONException: java.lang.NoSuchMethodException: cn.sunzn.json.Person.()
at net.sf.json.JSONObject.toBean(JSONObject.java:288)
at net.sf.json.JSONObject.toBean(JSONObject.java:233)
at cn.sunzn.json.JsonLib.main(JsonLib.java:23)
Caused by: java.lang.NoSuchMethodException: cn.sunzn.json.Person.()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getDeclaredConstructor(Unknown Source)
at net.sf.json.util.NewBeanInstanceStrategy$DefaultNewBeanInstanceStrategy.newInstance(NewBeanInstanceStrategy.java:55)
at net.sf.json.JSONObject.toBean(JSONObject.java:282)
… 2 more

Thank you for your support, if you want to understand the software industry, let's work hard together, and strive to add wei: zzaizhangzeng

Published 23 original articles · Like 11 · Visits 30,000+

Guess you like

Origin blog.csdn.net/weixin_42279584/article/details/88852555