Monday, February 1, 2016

Java: Convert JSON to DTO Object

Use Jakson

U can convert JSON to DTO and back automatically with ObjectMapper:
  • Convert Java object to JSON, writeValue(...)
  • Convert JSON to Java object, readValue(...)
  • Convert JSON to List of Java objects, readValues(...)
U can use field with different name with @JsonProperty(...) annotation.
U can skip unneeded properties with the following method: configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Convert JSON to DTO

   public class JsonToDtoTest {

      String usersJSON = "[" +
                            "{" +
                               "\"userId\":\"23746376473L\"," +
                               "\"username\":\"Joe\"," +
                               "\"phone\":\"43287377\"," +
                               "\"created\":\"2016-01-21T10:40:04.623Z\"" +
                            "}," +
                            "{" +
                               "\"userId\":\"23746376473L\"," +
                               "\"username\":\"Joe\"," +
                               "\"phone\":\"43287377\"," +
                               "\"created\":\"2016-01-21T10:40:04.623Z\"" +
                            "}]";

      class UserDto {

        @JsonProperty("userId")
        Long id;
        String username;

        public Long getId() { return id; }

        public void setId(Long id) {
            this.id = id;
        }

        public String getUsername() { return username; }

        public void setUsername(String username) {
            this.username = username;
        }

        @Override
        public String toString() {
            return "UserDto { id=" + id + "username=" + username + "};"
        }
      }

      @Test
      public void testParseJSON() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        ObjectReader reader = mapper.reader(UserDto.class);
        MappingIterator elements = reader.readValues(usersJSON);
        UserDto user = elements.next();
        Assert.assertEquals("23746376473L", user.getId());
        Assert.assertEquals("Joe", user.getUsername());
      }
    }

Deserialize an array of objects

    ...
    JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, UserDto.class);
    List users = mapper.readValue(usersJSON, type);



10 comments:

  1. Hello, please:

    How may I accomplish the same with BOTH a Model bean and a managed bean that connects the MODEL to a remote MySQL data source?

    http://stackoverflow.com/questions/41142802/jsf-managed-bean-accessing-mysql-remote-database-how-to-create-json-array-to-f

    Any suggestions greatly appreciated.

    Jon

    ReplyDelete
    Replies
    1. You can write converter that will convert DTO to Persisted Entity and back.
      Or you can serialize/deserialize persidtence Entity without intermediate layer. Each of approaches has own advantages & disadvantages.

      Delete
    2. Hello Andrew, thank you for your reply

      Delete

  2. Hi there everyone, I have come across almost all the web development sites. However, your website is far better than other in form of content, tools and easiness of using website. Since I am a developer, I am always looking forward to make people aware of web development tools. I can help you people out by introducing you to range of json tools. Here is the link jsononline



    ReplyDelete