Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chuyển Map thành JSONObject dùng JSON-lib API (Java)

JSONObject.accumulateAll(Map) thêm tất cả entry từ Map vào JSONObject. Key Map thành JSON key, Value Map (bean) thành nested JSONObject.

Cú pháp

public void accumulateAll(Map map)

Ví dụ minh họa

import net.sf.json.JSONObject;
import java.util.*;

public class MapToJsonObjectTest {
    public static void main(String[] args) throws Exception {
        JSONObject jsonObject = new JSONObject();
        Map<Integer, Employee> employees = new HashMap<>();
        
        employees.put(1, new Employee("Adithya", "Jai", 30));
        employees.put(2, new Employee("Vamsi", "Krishna", 28));
        employees.put(3, new Employee("Chaitanya", "Sai", 30));
        
        jsonObject.accumulateAll(employees);
        System.out.println(jsonObject.toString(3));
    }
    
    static class Employee {
        private String firstName, lastName;
        private int age;
        public Employee(String fn, String ln, int age) {
            this.firstName = fn; this.lastName = ln; this.age = age;
        }
        // getters...
    }
}

Output

{
  "1": { "firstName": "Adithya", "lastName": "Jai", "age": 30 },
  "2": { "firstName": "Vamsi", "lastName": "Krishna", "age": 28 },
  "3": { "firstName": "Chaitanya", "lastName": "Sai", "age": 30 }
}

Alternative: Jackson (Khuyến nghị)

ObjectMapper mapper = new ObjectMapper();
Map<Integer, Employee> employees = new HashMap<>();
// ... put data
String json = mapper.writeValueAsString(employees);
// Output giống hệt: {"1":{...},"2":{...},"3":{...}}

// Hoặc serialize Map trực tiếp không cần JSONObject wrapper

Lưu ý

  • Key Map phải serialize được thành JSON string (String, Number, Boolean).
  • Value Map nên là Bean/POJO có getter/setter.
  • JSON-lib **unmaintained**. Jackson/Gson handle Map tự nhiên, không cần JSONObject trung gian.
  • Jackson: mapper.writeValueAsString(map) serialize Map trực tiếp.