欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA对JSON字符串进行时间排序

程序员文章站 2024-03-24 19:42:34
...
[{
	"BEGDA": "0000-00-00",
	"ENDDA": "0000-00-00",
	"PERNR": "00000000",
	"USRID": "",
	"USRTY": ""
}, {
	"BEGDA": "2019-04-15",
	"ENDDA": "9999-12-31",
	"PERNR": "",
	"USRID": "17666294051",
	"USRTY": "MPHN"
}, {
	"BEGDA": "2020-01-01",
	"ENDDA": "9999-12-31",
	"PERNR": "10004398",
	"USRID": "12345678",
	"USRTY": "MAIL"
}, {
	"BEGDA": "2019-04-15",
	"ENDDA": "9999-12-31",
	"PERNR": "",
	"USRID": "17666294051",
	"USRTY": "MPHN"
}, {
	"BEGDA": "2020-01-01",
	"ENDDA": "9999-12-31",
	"PERNR": "",
	"USRID": "12345678",
	"USRTY": "MAIL"
}]

先看一下这端JSON格式,怎么弄得呢?字符串JSON,我怎么toString直接就可以生成JSON字符串呢?

JAVA对JSON字符串进行时间排序

	 


    //这个加到你JAVA类里面,this指针,指向自身类,然后你调用这个类接受数据库查询或者调用webservice回调得结果,都可以直接toString拿到JSON字符串
        @Override
		public String toString() {
			return JSONObject.fromObject(this).toString();
		}

 

 

需求是我们将以BEGDA排序,怎么排呢?

package com.sap.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

public class JsonArraySortOrderByDate {
	 /**
     * 按照JSONArray中的对象的某个字段进行排序(采用fastJson)
     * @param jsonArrStr json数组字符串
     * 
     * @param jsonArrStr keyName变量
     * 
     */
    public  String JsonOrderByDate(String jsonArrStr) {
        JSONArray jsonArr = JSON.parseArray(jsonArrStr);
        JSONArray sortedJsonArray = new JSONArray();
        List<JSONObject> jsonValues = new ArrayList<JSONObject>();
        for (int i = 0; i < jsonArr.size(); i++) {
            jsonValues.add(jsonArr.getJSONObject(i));
        }
        Collections.sort(jsonValues, new Comparator<JSONObject>() {
          private final String KEY_NAME = "ZXJRQ";
            String string1;
            String string2;
            @Override
            public int compare(JSONObject a, JSONObject b) {
        try {
                     string1= a.getString(KEY_NAME).replaceAll("-", "");
                     string2= b.getString(KEY_NAME).replaceAll("-", "");
                } catch (JSONException e) {
                    // 处理异常
                }
                    //这里是按照时间逆序排列,不加负号为正序排列
                return -string1.compareTo(string2);
            }
        });
        for (int i = 0; i < jsonArr.size(); i++) {
            sortedJsonArray.add(jsonValues.get(i));
        }
        return sortedJsonArray.toString();
    }
}

这一段,已经很明白了,假设你要联合排得话,将改造一下 

 

未结束~~~

相关标签: 个人心得