目錄
- 手動拼接(不推薦)
- 使用 Gson 等 JSON 庫
- 使用 JSONObject(推薦)
我的安卓開發經歷始于一個原生安卓項目開發。后來由于公司有個項目與幾家醫療設備公司合作,需要我寫安卓端的橋接代碼給 react native 端的同事調用。剛開始,對于一些流程的也不懂,直接調用 toString 就給 RN 了,給 RN 端的數據就是比如 {code=NOT_INITIALIZED, message=Please initialize library}
,導致 RN 端的同事需要自己寫解析代碼獲取 key 和 value,聯調麻煩。后來去研究如何轉成 json 字符串給 RN 端,聯調就順暢多了
下面以錯誤處理返回的 code 和 message 為例,演示如何拼接 JSON 字符串
// 演示數據 String code = "NOT_INITIALIZED"; String message = "Please initialize library";
手動拼接(不推薦)
我們看 json 的結構,key 和 string 類型的 value 的都是需要前后加雙引號的,java 沒有 js 的 ''
或 ``,那怎么插入雙引號呢,答案是使用反斜杠加字符串
對于 char
和 String
變量,拼接比較麻煩
char c1 = 'c'; String s1 = "s1"; System.out.println("{" + "\"c1\":" + "\"" + c1 + "\"" + "}"); System.out.println("{" + "\"s1\":" + "\"" + s1 + "\"" + "}");
其他類型的變量,拼接就比較簡單了
boolean b1 = true; float f1 = 34f; double d1 = 33.2d; System.out.println("{" + "\"b1\":" + b1 + "}"); System.out.println("{" + "\"f1\":" + f1 + "}"); System.out.println("{" + "\"d1\":" + d1 + "}");
因此,對于上面提到的數據,拼接的話就是下面這樣
String jsonStr = "{" + "\"code\":" + "\"" + code + "\"" + "," + "\"message\":" + "\"" + message + "\"" + "}";
為什么不推薦這種方式呢?數據量少還好,多了的話可能會遇到逗號忘寫,字符串忘加前后置反斜杠雙引號的情況,調試費時間
使用 Gson 等 JSON 庫
1.定義一個數據類
class ErrorInfo { private String code; private String message; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
2.使用 Gson 的 toJson 方法
import com.google.gson.Gson; ErrorInfo errorInfo = new ErrorInfo(); errorInfo.setCode(code); errorInfo.setMessage(message); Gson gson = new Gson(); String jsonStr = gson.toJson(errorInfo);
使用 JSONObject(推薦)
import org.json.JSONObject; JSONObject jsonObject = new JSONObject(); String jsonStr = ""; try { jsonObject.put("code", code); jsonObject.put("message", message); jsonStr = jsonObject.toString(); } catch (JSONException e) { throw new RuntimeException(e); }
為了避免 try catch,我更傾向于搭配 HashMap 使用
HashMap<String, String> map = new HashMap<>(); map.put("code", code); map.put("message", message); String jsonStr = new JSONObject(map).toString();
為什么推薦這種方式呢?兩個原因,第一,使用起來比前兩種方式都方便;第二,假如你是原生開發安卓的話,那你大概率會引入一個 JSON 庫來實現前后端配合,創建一個數據類搭配 GSON 可比 jsonObject.getString
使用起來方便多了,但像我司主要是 RN 項目,為了一個小功能而引入一個庫實在是不劃算,這時就是 JSONObject 的用武之地了