|
| 1 | +package com.baeldung.jackson.xmlToJson; |
| 2 | + |
| 3 | + |
| 4 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 5 | +import com.fasterxml.jackson.databind.JsonNode; |
| 6 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 7 | +import com.fasterxml.jackson.dataformat.xml.XmlMapper; |
| 8 | +import org.junit.Test; |
| 9 | + |
| 10 | +import static org.junit.Assert.*; |
| 11 | + |
| 12 | +import java.io.IOException; |
| 13 | + |
| 14 | +public class XmlToJsonUnitTest { |
| 15 | + |
| 16 | + @Test |
| 17 | + public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() { |
| 18 | + String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>"; |
| 19 | + |
| 20 | + try { |
| 21 | + XmlMapper xmlMapper = new XmlMapper(); |
| 22 | + Flower poppy = xmlMapper.readValue(flowerXML, Flower.class); |
| 23 | + |
| 24 | + assertEquals(poppy.getName(), "Poppy"); |
| 25 | + assertEquals(poppy.getColor(), Color.RED); |
| 26 | + assertEquals(poppy.getPetals(), new Integer(9)); |
| 27 | + |
| 28 | + ObjectMapper mapper = new ObjectMapper(); |
| 29 | + String json = mapper.writeValueAsString(poppy); |
| 30 | + |
| 31 | + assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}"); |
| 32 | + System.out.println(json); |
| 33 | + } catch(IOException e) { |
| 34 | + e.printStackTrace(); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + @Test |
| 39 | + public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() { |
| 40 | + String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>"; |
| 41 | + |
| 42 | + try { |
| 43 | + XmlMapper xmlMapper = new XmlMapper(); |
| 44 | + JsonNode node = xmlMapper.readTree(flowerXML.getBytes()); |
| 45 | + |
| 46 | + ObjectMapper jsonMapper = new ObjectMapper(); |
| 47 | + String json = jsonMapper.writeValueAsString(node); |
| 48 | + |
| 49 | + System.out.println(json); |
| 50 | + |
| 51 | + assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}"); |
| 52 | + } catch(IOException e) { |
| 53 | + e.printStackTrace(); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments