Created
July 27, 2018 12:28
-
-
Save yati-sagade/4b1143d6987ee059d228209da30fc747 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import com.fasterxml.jackson.annotation.JsonProperty; | |
| import com.fasterxml.jackson.core.JsonParser; | |
| import com.fasterxml.jackson.core.JsonProcessingException; | |
| import com.fasterxml.jackson.databind.DeserializationContext; | |
| import com.fasterxml.jackson.databind.JsonDeserializer; | |
| import com.fasterxml.jackson.databind.ObjectMapper; | |
| import com.fasterxml.jackson.databind.annotation.JsonDeserialize; | |
| import java.io.IOException; | |
| import java.util.*; | |
| public class JacksonPlayground { | |
| static class TopicOffset { | |
| public long offset; | |
| public String topic; | |
| public TopicOffset(String topic, long offset) { | |
| this.offset = offset; | |
| this.topic = topic; | |
| } | |
| } | |
| static class State { | |
| @JsonProperty("topic_offsets") | |
| @JsonDeserialize(using = TopicOffsetDeserializer.class) | |
| List<TopicOffset> topicOffsets; | |
| } | |
| static class TopicOffsetDeserializer extends JsonDeserializer<List<TopicOffset>> { | |
| public List<TopicOffset> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { | |
| System.out.println("Custom deser called"); | |
| final Iterator<Object[]> it = jsonParser.readValuesAs(Object[].class); | |
| Iterable<Object[]> iterable = () -> it; | |
| List<Object[]> topicAndOffsetList = new ArrayList<Object[]>(); | |
| for (Object[] objects : iterable) { | |
| topicAndOffsetList.add(objects); | |
| } | |
| System.out.println("We have a list of " + topicAndOffsetList.size() + " topic/offsets"); | |
| List<TopicOffset> topicOffsets = new ArrayList<>(topicAndOffsetList.size()); | |
| for (Object[] topicAndOffset : topicAndOffsetList) { | |
| String topic = (String) topicAndOffset[0]; | |
| long offset = (long) topicAndOffset[1]; | |
| System.out.println("Handling " + topic + ", " + offset + " now."); | |
| topicOffsets.add(new TopicOffset(topic, offset)); | |
| } | |
| return topicOffsets; | |
| } | |
| } | |
| public static void main(String[] args) throws Exception { | |
| String json = "{\"topic_offsets\": [[\"lama\", 0]]}"; | |
| ObjectMapper objectMapper = new ObjectMapper(); | |
| State state = objectMapper.readValue(json, State.class); | |
| for (TopicOffset topicOffset : state.topicOffsets) { | |
| System.out.printf("Topic %s, offset %d", topicOffset.topic, topicOffset.offset); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment