需將勾選的商品列表轉為 JSON:{users:[{name:"acx",uid:"2"},{name:"test",uid:"6"}]}。原代碼錯用 List<String> 存放 JSON 字串,導致輸出雙重轉義 {\"users\":\"[{\\\"uid\\\":\\\"4\\\"}]\"}。正確做法是構建 JSONObject/JSONArray 物件樹,最後一次性序列化。
List list = new ArrayList<>();
for (Product p : boxAdapter.getBox()) {
if (p.checked) {
JSONObject jChild = new JSONObject();
jChild.put("uid", p.uid);
list.add(jChild.toString()); // ❌ 存字串,非物件
}
}
jParent.put("users", list); // list 被當作字串數組序列化
// 輸出: {"users":"[{\"uid\":\"4\"},{\"uid\":\"5\"}]"}
private void buildJson() {
try {
JSONObject jParent = new JSONObject();
JSONArray jArray = new JSONArray(); // 關鍵:用 JSONArray 而非 List
for (Product p : boxAdapter.getBox()) {
if (p.checked) {
JSONObject jItem = new JSONObject();
jItem.put("name", p.name); // 補充 name 字段
jItem.put("uid", p.uid);
jArray.put(jItem); // 直接放 JSONObject
}
}
jParent.put("users", jArray); // 放 JSONArray
String jsonStr = jParent.toString(); // 一次性序列化
// {"users":[{"name":"acx","uid":"2"},{"name":"test","uid":"6"}]}
Log.v("JSON", jsonStr);
} catch (JSONException e) {
e.printStackTrace();
}
}
| 錯誤做法 | 正確做法 |
|---|---|
List 存 toString() | JSONArray 存 JSONObject |
| 多次序列化產生雙重轉義 | 構建完整物件樹,最後 toString() 一次 |
| 類型擦除導致 JSONArray 變字串 | 保持強類型物件結構 |
// 1. 定義數據類
class UserItem {
String name;
String uid;
}
class Response {
List users;
}
// 2. 直接構建對象
Response resp = new Response();
resp.users = new ArrayList<>();
for (Product p : boxAdapter.getBox()) {
if (p.checked) {
UserItem item = new UserItem();
item.name = p.name;
item.uid = p.uid;
resp.users.add(item);
}
}
// 3. 一行序列化
String json = new Gson().toJson(resp);
// {"users":[{"name":"acx","uid":"2"},{"name":"test","uid":"6"}]}
優點:類型安全、無需手動 put、自動處理 null、支援泛型、性能更好。
JSON 嵌套結構構建核心:用 JSONArray 承載 JSONObject 列表,最後根節點 put JSONArray。避免中間轉字串存 List。生產環境首選 Gson/Jackson 自動序列化,減少手工錯誤。