BAEL-2237 Using Jackson to parse XML and return JSON (#5478)

This commit is contained in:
Felipe Santiago Corro 2018-10-17 14:29:47 -03:00 committed by maibin
parent 6cabd68be5
commit 99d309b8c2
1 changed files with 15 additions and 28 deletions

View File

@ -1,7 +1,5 @@
package com.baeldung.jackson.xmlToJson; package com.baeldung.jackson.xmlToJson;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@ -14,10 +12,9 @@ import java.io.IOException;
public class XmlToJsonUnitTest { public class XmlToJsonUnitTest {
@Test @Test
public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() { public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() throws IOException{
String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>"; String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>";
try {
XmlMapper xmlMapper = new XmlMapper(); XmlMapper xmlMapper = new XmlMapper();
Flower poppy = xmlMapper.readValue(flowerXML, Flower.class); Flower poppy = xmlMapper.readValue(flowerXML, Flower.class);
@ -29,28 +26,18 @@ public class XmlToJsonUnitTest {
String json = mapper.writeValueAsString(poppy); String json = mapper.writeValueAsString(poppy);
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}"); assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}");
System.out.println(json);
} catch(IOException e) {
e.printStackTrace();
}
} }
@Test @Test
public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() { public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() throws IOException {
String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>"; String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>";
try {
XmlMapper xmlMapper = new XmlMapper(); XmlMapper xmlMapper = new XmlMapper();
JsonNode node = xmlMapper.readTree(flowerXML.getBytes()); JsonNode node = xmlMapper.readTree(flowerXML.getBytes());
ObjectMapper jsonMapper = new ObjectMapper(); ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(node); String json = jsonMapper.writeValueAsString(node);
System.out.println(json);
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}"); assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}");
} catch(IOException e) {
e.printStackTrace();
}
} }
} }