Guest User

Untitled

a guest
Jul 4th, 2016
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. package com.mkyong.json;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.math.BigDecimal;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9. import com.fasterxml.jackson.core.JsonGenerationException;
  10. import com.fasterxml.jackson.databind.JsonMappingException;
  11. import com.fasterxml.jackson.databind.ObjectMapper;
  12.  
  13. public class Jackson2Example {
  14.  
  15. public static void main(String[] args) {
  16. Jackson2Example obj = new Jackson2Example();
  17. obj.run();
  18. }
  19.  
  20. private void run() {
  21. ObjectMapper mapper = new ObjectMapper();
  22.  
  23. Staff staff = createDummyObject();
  24.  
  25. try {
  26. // Convert object to JSON string and save into a file directly
  27. mapper.writeValue(new File("D:\\staff.json"), staff);
  28.  
  29. // Convert object to JSON string
  30. String jsonInString = mapper.writeValueAsString(staff);
  31. System.out.println(jsonInString);
  32.  
  33. // Convert object to JSON string and pretty print
  34. jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);
  35. System.out.println(jsonInString);
  36.  
  37. } catch (JsonGenerationException e) {
  38. e.printStackTrace();
  39. } catch (JsonMappingException e) {
  40. e.printStackTrace();
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45.  
  46. private Staff createDummyObject() {
  47.  
  48. Staff staff = new Staff();
  49.  
  50. staff.setName("mkyong");
  51. staff.setAge(33);
  52. staff.setPosition("Developer");
  53. staff.setSalary(new BigDecimal("7500"));
  54.  
  55. List<String> skills = new ArrayList<>();
  56. skills.add("java");
  57. skills.add("python");
  58.  
  59. staff.setSkills(skills);
  60.  
  61. return staff;
  62.  
  63. }
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment