Boon - 从映射



ObjectMapper 类可以用于从映射生成 json 字符串。

实例

以下实例使用 ObjectMapper 类从映射对象生成 JSON 字符串。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.boon.json.JsonFactory;
import org.boon.json.ObjectMapper;

public class BoonTester {
   public static void main(String args[]){
      ObjectMapper mapper = JsonFactory.create();      
      Map<String, String> student = new HashMap<>();
      student.put("Name", "Mahesh");
      student.put("RollNo", "21");
      
      Map<String, String> student1 = new HashMap<>();
      student1.put("Name", "Suresh");
      student1.put("RollNo", "22");
      
      List<Map<String,String>> studentList = new ArrayList<>();
      studentList.add(student);
      studentList.add(student1);
      
      Map<String, List> studentMap = new HashMap<String, List>();
      studentMap.put("students", studentList);
      
      String jsonString = mapper.writeValueAsString(studentMap);
      System.out.println(jsonString);
   }
}

输出

当你执行上述代码时,你应该会看到如下输出 −

{"students":[{"RollNo":"21","Name":"Mahesh"},{"RollNo":"22","Name":"Suresh"}]}
广告