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

This commit is contained in:
Felipe Santiago Corro 2018-10-08 03:36:38 -03:00 committed by maibin
parent acf37e52ef
commit f046857975
4 changed files with 104 additions and 1 deletions

View File

@ -118,7 +118,7 @@
<properties>
<!-- marshalling -->
<jackson.version>2.9.6</jackson.version>
<jackson.version>2.9.7</jackson.version>
<!-- util -->
<commons-lang3.version>3.8</commons-lang3.version>
<joda-time.version>2.10</joda-time.version>

View File

@ -0,0 +1,5 @@
package com.baeldung.jackson.xmlToJson;
public enum Color {
PINK, BLUE, YELLOW, RED;
}

View File

@ -0,0 +1,42 @@
package com.baeldung.jackson.xmlToJson;
public class Flower {
private String name;
private Color color;
private Integer petals;
public Flower() { }
public Flower(String name, Color color, Integer petals) {
this.name = name;
this.color = color;
this.petals = petals;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Integer getPetals() {
return petals;
}
public void setPetals(Integer petals) {
this.petals = petals;
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.jackson.xmlToJson;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.IOException;
public class XmlToJsonUnitTest {
@Test
public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() {
String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>";
try {
XmlMapper xmlMapper = new XmlMapper();
Flower poppy = xmlMapper.readValue(flowerXML, Flower.class);
assertEquals(poppy.getName(), "Poppy");
assertEquals(poppy.getColor(), Color.RED);
assertEquals(poppy.getPetals(), new Integer(9));
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(poppy);
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}");
System.out.println(json);
} catch(IOException e) {
e.printStackTrace();
}
}
@Test
public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() {
String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>";
try {
XmlMapper xmlMapper = new XmlMapper();
JsonNode node = xmlMapper.readTree(flowerXML.getBytes());
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(node);
System.out.println(json);
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}");
} catch(IOException e) {
e.printStackTrace();
}
}
}