Usage and business scenarios of JSONObject and JSONArray

Recently took over a business installment payment is required by payment type , staging periods to find the corresponding rates . It involves the use of JSONObject and JSONArray.

Introduce fastjson dependency, The following code of copy and paste pom.xml <dependencies>... </dependencies>in

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.46</version>
</dependency>          

1. Business scenario application

The json string passed in by the installment payment service is as follows:

{
    
    
	"花呗": [{
    
     //分期支付产品类型
		"instalmentNum": "6期",  //分期的期数
		"repaymentRate": "20.50%" //费率
	}, {
    
    
		"instalmentNum": "12期",
		"repaymentRate": "25.00%"
	}, {
    
    
		"instalmentNum": "24期",
		"repaymentRate": "13.00%"
	}, {
    
    
		"instalmentNum": "36期",
		"repaymentRate": "18.00%"
	}]
}

(The above values ​​are made randomly, the key point is how to use JSONObject and JSONArray below)

Now I have to pay by installments type (a chant), staging periods (6) to find the corresponding rate of 20.50%

Remove Rate 20.50% steps:

  • First get the value corresponding to Huabei: {"Huabei": value} The whole is a JSONObject, in the form of a key-value pair
  • "Flower chant" corresponding to the value is a JSONArray, 形式如: [ {key:value}, {}, {} ], wherein the square brackets is the representative of a JSONArray, array inside each key-value pair is a form of {key: value}, is a type java.lang.Object

The project uses fastjson, so the following method is also based on this jar package


//入参repaymentRate是上面的那个json串
private static matchRepaymentRate(String repaymentRate){
    
    
	//先拿到repaymentRate对应的json键值对形式{ "花呗": value }
	JSONObject jsonObject=JSONObject.parseObject(repaymentRate);
	//再拿到key(花呗)对应的value,是一个JSONArray,形如[{key:value},{..},{..}]
	JSONArray jsonArray=jsonObject.getJSONArray("花呗");
	for(int i=0;i<jsonArray.size();i++){
    
    
		 //得到数组的第i个元素,即{"instalmentNum": "6期","repaymentRate": "20.50%"}
         JSONObject jsonObj= jsonArray.getJSONObject(i);
         String instalmentNum=jsonObj.getString("instalmentNum");
         if(instalmentNum.equals("6期")){
    
    
             System.out.println("分期支付的类型是花呗 、分期6期得到的费率为:"+jsonObj.getString("repaymentRate"));
         }
    }
}

Payment type (some chant) + 6 installments => the rate is 20.50%, the result is as follows

Payment type Huabei + 6 installments to get the corresponding rate

Second, JSONObject

JSONObject is a key-value pair, which is shaped like {key: value }. Later, when you see {} braces, it can be regarded as a JSONObject.

itThe inside is actually a Map<String, Object> map, Can be HashMap, or LinkedHashMap

Construction method

  • Default construction: What you get is a HashMap with an initial capacity of 16, public JSONObject() { this(16, false); }where false is to construct a HashMap, and true is to construct a LinkedHashMap
  • The artificial designation is to construct a HashMap or a LinkedHashMap (but the initial capacity cannot be specified):public JSONObject(boolean ordered) { this(16, ordered); }
  • Manually specify the capacity of HashMap (not LinkedHashMap):public JSONObject(int initialCapacity)
  • At the same time, the initial capacity and container type can be specified:
public JSONObject(int initialCapacity, boolean ordered) {
    
    
     if (ordered) {
    
    
        this.map = new LinkedHashMap(initialCapacity);
     } else {
    
    
        this.map = new HashMap(initialCapacity);
     }
}

JSONObject commonly used API

  • public Object get(Object key): Called the Map.get(key) method
  • public JSONObject getJSONObject(String key): Obtaining a JSONObject object because Map <Stirng, Object> value is the Object, so return to cast JSONObject , i.e. (JSONObject) value
  • public JSONArray getJSONArray(String key): Get a JSONArray array, the method will return a (JSONArray) map.get(key)

There are other getString(String key) and getDouble(String key) that convert the Object value to the corresponding type and return

Three, JSONArray

JSONArray is essentially one List<Object>, and the following API is also based on List operations

Construction method

There are three construction methods:

  • Default structure:public JSONArray() { this.list = new ArrayList(); }
  • The structure of a List collection can be passed in:public JSONArray(List<Object> list) { this.list = list; }
  • JSONArray(int initialCapacity) Set the initial capacity of the List

JSONArray commonly used API

  • JSONObject getJSONObject(int index) Obtain the element at the specified position, using forced type conversion: (JSONObject) list.get(index)
  • JSONArray getJSONArray(int index): The element at the specified position obtained is (JSONArray) list.get(index), a JSONArray array
  • String getString(int index): Return the element at the specified position, and turn the original Object element into a String element
  • JSONArray getJSONArray(int index): Obtaining inner nested in JSON array, such that:
{
    
    
	"成绩排名":[   //外层json数组
		{
    
    
			"第一名":[{
    
    "姓名":"小明"},{
    
    "学号":"1"}]  //内层json数组
		},{
    
    
			"第二名":[{
    
    "姓名":"二狗子"},{
    
    "学号":"2"}]
		}
	]
}

There are 2 levels of JSONArray nested in the json string, with 2 levels of square brackets []. If
I want to know who is the first, the operation is as follows:

String str ="{\"成绩排名\": ... }"
JSONObject jsonObject=JSON.parseObject(str);
//拿到了外层json数组:[{"第一名":[{"姓名":"小明"},{"学号":"1"}]}, {..}]
JSONArray jsonArray=jsonObject.getJSONArray("成绩排名");
for(int i=0;i<jsonArray.size();i++){
    
    
	JSONObject jsonObj=jsonArray.getJSONObject(i);
	//拿到了内层的json数组:[{"姓名":"小明"},{"学号":"1"}]
	JSONArray jsonArr =jsonObj.getJSONArray("第一名");
    for(int j=0;jsonArr!=null&&j<jsonArr.size();j++){
    
    
    	//拿到了JSONObject {"姓名":"小明"}
    	JSONObject json =jsonArr.getJSONObject(j);
    	System.out.println(json.getString("姓名"));
    }
}

Use of JSONObject and JSONArray

(1) Add key-value pairs to a json object, and add json objects to the JSONArray array

//json添加键值对
JSONObject jsonObject=new JSONObject();
jsonObject.put("key","value");

//在JSONArray添加json对象
JSONArray jsonArray=new JSONArray();
jsonArray.add(jsonObject);

(2) Convert String type json string to JSONObject and JSONArray

① Convert String to JSONObject

String str = "{ \"name\":\"小明\" }";
JSONObject jsonObject=JSON.parseObject(str);

② Convert String to JSONArray

String str = "[{ \"name\":\"小明\" }]";
JSONArray jsonArray=JSON.parseArray(str);
System.out.println( jsonArray.getJSONObject(0));

Output: { "name": "Bob"}, if not json string "[]" brackets, it is unable to obtain the element from the specified location , either jsonArray.get (0) or jsonArray.getJSONObject (0 ) Will throw an exception, without square brackets [], the format is incorrect.

Guess you like

Origin blog.csdn.net/qq_44384533/article/details/111152885