소스 검색

filterNullAttributes

deason 7 년 전
부모
커밋
c8c193a227
2개의 변경된 파일30개의 추가작업 그리고 1개의 파일을 삭제
  1. 5 0
      pom.xml
  2. 25 1
      src/main/java/cn/com/qmth/examcloud/app/utils/HttpUtils.java

+ 5 - 0
pom.xml

@@ -55,6 +55,11 @@
             <artifactId>jsoup</artifactId>
             <version>1.11.3</version>
         </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <version>1.2.47</version>
+        </dependency>
         <dependency>
             <groupId>com.google.guava</groupId>
             <artifactId>guava</artifactId>

+ 25 - 1
src/main/java/cn/com/qmth/examcloud/app/utils/HttpUtils.java

@@ -10,9 +10,11 @@ package cn.com.qmth.examcloud.app.utils;
 import cn.com.qmth.examcloud.app.model.Constants;
 import cn.com.qmth.examcloud.app.model.ResBody;
 import cn.com.qmth.examcloud.app.model.Result;
+import com.alibaba.fastjson.JSON;
 import okhttp3.Request;
 import okhttp3.RequestBody;
 import okhttp3.Response;
+import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -65,7 +67,8 @@ public class HttpUtils {
         Response response = HttpBuilder.client.getInstance().newCall(request).execute();
         String bodyStr = response.body().string();
         if (response.isSuccessful()) {
-            return new Result().success(bodyStr);
+            String data = HttpUtils.filterNullAttributes(bodyStr);
+            return new Result().success(data);
         } else {
             log.warn("[Response] " + bodyStr);
             ResBody body = new JsonMapper().fromJson(bodyStr, ResBody.class);
@@ -85,4 +88,25 @@ public class HttpUtils {
         }
     }
 
+    /**
+     * 如果是JSON字符串,则过滤掉为空的属性
+     */
+    public static String filterNullAttributes(String str) {
+        if (StringUtils.isBlank(str)) {
+            return "";
+        }
+        try {
+            Object obj = JSON.parse(str);
+            return obj.toString();
+        } catch (Exception e) {
+            return str;
+        }
+    }
+
+    /*public static void main(String[] args) {
+        String json = "{\"id\":1,\"answer\":null,\"question\":{\"id\":2,\"answer\":null,\"question\":{\"id\":3,\"answer\":null,\"question\":{\"id\":4,\"answer\":null,,\"question\":{\"id\":5,\"answer\":null}}}}}";
+        String result = HttpUtils.filterNullAttributes(json);
+        System.out.println(result);
+    }*/
+
 }