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

javajsonobject oriented programmingprogramming

JSONObject名称/值 对的无序集合,而 Map 是将键映射到值的对象。Map 不能包含重复的,并且每个键最多可以映射到一个值。我们需要使用 JSON-lib 库以 JSON 格式对 Map 进行序列化反序列化。首先,我们可以创建一个 POJO 类并将该实例作为参数传递给 Map  类的 put() 方法,最后将该 map 实例添加到 JSONObject 的 accumulateAll() 方法。

语法

public void precipitateAll(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
 }
}

相关文章