语法
public void accumulateall(Map map)
在下面的示例中,我们可以将 Map 转换为 JSON 对象。
示例
import java.util.*; import net.sf.json.JSONObject; public class ConvertMapToJSONObjectTest { public static void main(String[] args)throws Exception { JSONObject jsonObject = new JSONObject(); Map<Integer, Employee> employees = new HashMap<Integer, Employee>(); 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; } } }
输出
{ "1": { "firstName": "Adithya", "lastName": "Jai", "age": 30 }, "2": { "firstName": "Vamsi", "lastName": "Krishna", "age": 28 }, "3": { "firstName": "Chaitanya", "lastName": "Sai", "age": 30 } }
以上就是如何使用Java中的JSON-lib API将Map转换为JSON对象?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。