public class JacksonTest { private String name = null; private int age = 0; private String[] emails = null; private java.util.List< String> favorites = null; private String mobile = null; public JacksonTest() { } public JacksonTest( String name, int age, String[] emails, java.util.List< String> favorites, String mobile) { this.name = name; this.age = age; this.emails = emails; this.favorites = favorites; this.mobile = mobile; } public String getName() { return name; } public int getAge() { return age; } public String[] getEmails() { return this.emails; } public void setEmails(String[] emails) { this.emails = emails; } public java.util.List<String> getFavorites() { return this.favorites; } public void setFavorites(java.util.List<String> favorites) { this.favorites = favorites; } public String getMobile() { return this.mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public static void main(String[] args) throws IOException { JacksonTest jackson = new JacksonTest( "dorbae", 27, new String[] { "jangsb89@gamil.com", "dorbae@nate.com"}, null, null ); java.util.List< String> favorites = new java.util.ArrayList< String>(); favorites.add( "programming"); favorites.add( "data analytics"); favorites.add( "data modeling"); favorites.add( "swimming"); jackson.setFavorites( favorites); JacksonTest jackson2 = null; // Object -> JSON com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); String json = mapper.writeValueAsString( jackson); System.out.println( "======== Object -> JSON ========"); System.out.printf( "%s\n\n", json); // JSON -> Object mapper = new ObjectMapper(); jackson2 = mapper.readValue( json, JacksonTest.class); System.out.println( "======== JSON -> Object ========"); System.out.printf( "name=%s, age=%d\n", jackson2.getName(), jackson2.getAge()); } }
Friday, 12 August 2016
[JSON] Convert object to json and convert json to object using Jackson
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment