点关注不迷路

Max

Java中JSONObject相关操作

 

 maven项目pom配置:

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

 

 

import net.sf.json.JSONObject;

//报文    
String report="{\"SEND_TIME\":\"20170509235000\",\"AREA_SOURCE\":\"ZSQD\",\"ACID\":\"QDA9772\",\"TASK\":\"W/Z\","
                + "\"PLAN_SOURCE\":\"QDNEXTPLAN\",\"ADEP\":\"ZUUU\",\"ADES\":\"ZSQD\",\"STOD\":\"0240\",\"STOA\":\"0525\","
                + "\"ETOT\":\"0240\",\"ELDT\":\"0525\",\"AIRCRAFT_TYPE\":\"A320\",\"REGID\":\"B1648\",\"EXECUTE_DATE\":\"20170510\"}";
//转json对象(反序列化)
JSONObject jsonObject = JSONObject.fromObject(report);  
//强转成PlanReport类
PlanReport hbreport=(PlanReport)JSONObject.toBean(jsonObject,PlanReport.class);

//序列化

jsonObject.toString();

 

//json合并 相同的字段会被后一个覆盖
JSONObject oldjson1=new JSONObject();

oldjson1.put("name", "zhangsan");

JSONObject oldjson2=new JSONObject();

oldjson2.put("name", "lisi");
oldjson2.put("age", "20");

//合并后的json
JSONObject newjson=new JSONObject();

newjson.putAll(oldjson1);
newjson.putAll(oldjson2);

json对比:

/**
 * 
 * 对比json对象中不同的value
 * 
 */
    public static String compareJson(JSONObject json1, JSONObject json2,String key) {
        String str="";
        @SuppressWarnings("unchecked")
        Iterator<String> i = json1.keys();
        while (i.hasNext()) {
            key =  i.next();
            str+= compareJson(json1.get(key), json2.get(key),key);
        }  
        return str;
    }
    public static String compareJson(Object json1,Object json2,String key) {
        String str ="";
        if (  json1   instanceof   JSONObject ) {
            str=compareJson((JSONObject)  json1  ,(JSONObject)   json2,key);
        }else if (  json1   instanceof   JSONArray  ) {
            compareJson((JSONArray)  json1  ,(JSONArray)   json2,key);
        }else if(json1 instanceof String   ){
            str=compareJson((String)  json1  ,(String)   json2,key);
        }else {
            str=compareJson(json1.toString(), json2.toString(), key);
        }
        return str;
    }
    public static String compareJson(String  str1,String str2,String key) {
        String str="";
        if (!str1.equals(str2)&& str2!=null) {
            //System.out.println("字段更新:"+key+ ",原报文数据:"+ str1 +",新报文数据:"+str2);
            str="字段更新:"+key+ ",原报文数据:"+ str1 +",新报文数据:"+str2+" ";
        }
        return str;
    }
    public static void compareJson(JSONArray json1,JSONArray json2,String key) {
        Iterator<?> i1= json1.iterator();
        Iterator<?> i2= json2.iterator();
        while ( i1.hasNext()) {
            compareJson(i1.next(), i2.next(),key);
        }
    }

json中不同字段对比,可以先转换成类再用反射技术进行对比

//通过反射获取到不同的属性
List<String> textList = Lists.newArrayList();  
String jsonstr="";
try { Class<? extends PlanReport> clazz = hbreport.getClass(); Field[] fields = hbreport.getClass().getDeclaredFields(); for (Field field : fields) { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz); Method getMethod = pd.getReadMethod(); Object o1 = getMethod.invoke(oldreport); Object o2 = getMethod.invoke(hbreport); String s1 = o1 == null ? "" : o1.toString();//避免空指针异常 String s2 = o2 == null ? "" : o2.toString();//避免空指针异常 if (!s1.contains(s2)) { textList.add("字段新增:" + field.getName() + " 字段值:" + s2 + " "); } } } catch (Exception e) { logger.info("计划日志字段新增反射异常日志打印 [{}]", e); System.out.println(e.getMessage()); } for (String object : textList) { jsonstr+=object; }

 JSONArray遍历:转换Iterator(迭代器)进行遍历

String str = "[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]" ;
JSONArray jsonarr = JSONArray.fromObject(str );
Iterator<Object> it = jsonarr.iterator();
while (it.hasNext()) {
    JSONObject jsonObject = (JSONObject) it.next();
    System.out.println(jsonObject.toString());
}

 JSONArray 中按照某个Key排序:

JSONArray JsonArray=new JSONArray();
JsonArray.add(***);
//从小到大 JsonArray.sort(
new Comparator<JSONObject>() { @Override public int compare(JSONObject o1, JSONObject o2) { return o1.getString("SEND_TIME").compareTo(o2.getString("SEND_TIME")); } });

 

posted @ 2017-06-07 15:59  Max麦克斯  阅读(29096)  评论(0编辑  收藏  举报