簡體   English   中英

將字節數組轉換為JSON錯誤無效的JSON

[英]Convert byte array to JSON error invalid JSON

我正在嘗試將byte[]轉換為類似於以下內容的JSON: {"foo": [{...}, {...}, ...], "bar": []}

try {
  byte[] response = getExternalServiceResponse();
  JSONObject json = new JSONObject(new String(response));
  log.info(json.toString(4));
} catch (Exception e) {
  e.printStackTrace();
}

這適用於大多數響應情況,但是有些響應會引發org.json.JSONException: A JSONObject text must begin with '{' at 3 [character 2 line 2]異常org.json.JSONException: A JSONObject text must begin with '{' at 3 [character 2 line 2] 我如何找出導致錯誤的原因是什么字符,因為我無法讀取字節數組,而且我不確定輸入中包含的內容,而不先將其轉換為引發錯誤的JSON?

我同意使用Exception判斷不是一個好主意。 也許您可以輕易地告訴它無效。

byte[] response = getExternalServiceResponse();
String resStr = new String(response).trim();
if(!resStr.startWith("{")) throw Exception("invalid json input!");

也許是因為有時您的服務會返回錯誤或類似於json的錯誤 ,例如“此處發生了一些錯誤!;-)”

最好在將響應轉換為json之前記錄您的響應,甚至更好地驗證其json模式以進行生產部署。

String strResponse = new String(response).trim();
log.info( strResponse);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM