Created
February 27, 2019 23:31
-
-
Save pinei/e05454e9ec1fe03724b97c111bd7da75 to your computer and use it in GitHub Desktop.
Translating String[] to JSON and JSON to String[] with Jackson
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.core.JsonProcessingException; | |
| import com.fasterxml.jackson.databind.ObjectMapper; | |
| import org.junit.Test; | |
| import java.io.IOException; | |
| import static org.junit.Assert.assertEquals; | |
| public class JacksonTest { | |
| @Test | |
| public void testArrayToJson() { | |
| String[] parameters = { "apple", "lemon", "banana" }; | |
| ObjectMapper objectMapper = new ObjectMapper(); | |
| String list = null; | |
| try { | |
| list = objectMapper.writeValueAsString(parameters); | |
| } catch (JsonProcessingException ex ) { | |
| } | |
| assertEquals(list, "[\"apple\",\"lemon\",\"banana\"]"); | |
| } | |
| @Test | |
| public void testJsonToArray() { | |
| ObjectMapper objectMapper = new ObjectMapper(); | |
| String jsonList = "[\"apple\", \"lemon\", \"banana\"]"; | |
| String[] list = null; | |
| try { | |
| list = objectMapper.readValue(jsonList, String[].class); | |
| } catch (IOException e) { | |
| } | |
| assertEquals(list[0], "apple"); | |
| assertEquals(list[1], "lemon"); | |
| assertEquals(list[2], "banana"); | |
| } | |
| @Test | |
| public void testEmptyArrayToJson() { | |
| String[] parameters = { }; | |
| ObjectMapper objectMapper = new ObjectMapper(); | |
| String list = null; | |
| try { | |
| list = objectMapper.writeValueAsString(parameters); | |
| } catch (JsonProcessingException ex ) { | |
| } | |
| assertEquals(list, "[]"); | |
| } | |
| @Test | |
| public void testEmptyJsonToArray() { | |
| ObjectMapper objectMapper = new ObjectMapper(); | |
| String jsonList = "[]"; | |
| String[] list = null; | |
| try { | |
| list = objectMapper.readValue(jsonList, String[].class); | |
| } catch (IOException e) { | |
| } | |
| assertEquals(list.length, 0); | |
| } | |
| @Test | |
| public void testArrayWithTextToJsonAndBackToArray() { | |
| String text = "\"Be or not to be\nThat's the question\"\n(Shakespare)"; | |
| String[] parameters = { text }; | |
| ObjectMapper objectMapper = new ObjectMapper(); | |
| String[] list = null; | |
| try { | |
| String jsonList = objectMapper.writeValueAsString(parameters); | |
| list = objectMapper.readValue(jsonList, String[].class); | |
| } | |
| catch (JsonProcessingException ex ) { | |
| } | |
| catch (IOException ex) { | |
| } | |
| assertEquals(list.length, 1); | |
| assertEquals(list[0], text); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment