如何使用Java中的JSONlib API将Map转换为JSON对象?

如何使用Java中的JSON-lib API将Map转换为JSON对象?

语法

public void accumulateAll(Map map)登录后复制

示例

import java.util.*; import net.sf.json.JSONObject; public class ConvertMapToJSONObjectTest { public static void main(String[] args)throws Exception { JSONObject jsonObject = new JSONObject(); Map 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)); // pretty print JSON } public static class Employee { private String firstName, lastName; private int age; public Employee(String firstName, String lastName, int age) { super(); this.firstName = firstName; this.lastName = lastName; this.age = age; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } } }登录后复制