Skip to content

Commit 3e3079e

Browse files
committed
added xml folder in jackson module,have no idea what am doing :)
1 parent 3896065 commit 3e3079e

1 file changed

Lines changed: 80 additions & 0 deletions

File tree

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package com.baeldung.jackson.xml;
2+
3+
import static org.junit.Assert.assertNotNull;
4+
import static org.junit.Assert.assertTrue;
5+
6+
import java.io.BufferedReader;
7+
import java.io.File;
8+
import java.io.FileInputStream;
9+
import java.io.IOException;
10+
import java.io.InputStream;
11+
import java.io.InputStreamReader;
12+
13+
import org.junit.Test;
14+
15+
import com.fasterxml.jackson.core.JsonProcessingException;
16+
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
17+
18+
public class TestClass {
19+
20+
@Test
21+
public void whenJavaSerializedToXmlStr_thenCorrect() throws JsonProcessingException{
22+
XmlMapper xmlMapper = new XmlMapper();
23+
String xml = xmlMapper.writeValueAsString(new SimpleBean());
24+
assertNotNull(xml);
25+
}
26+
@Test
27+
public void whenJavaSerializedToXmlFile_thenCorrect() throws IOException{
28+
XmlMapper xmlMapper = new XmlMapper();
29+
xmlMapper.writeValue(new File("simple_bean.xml"), new SimpleBean());
30+
File file=new File("simple_bean.xml");
31+
assertNotNull(file);
32+
}
33+
@Test
34+
public void whenJavaGotFromXmlStr_thenCorrect() throws IOException {
35+
XmlMapper xmlMapper = new XmlMapper();
36+
SimpleBean value = xmlMapper.readValue(
37+
"<SimpleBean><x>1</x><y>2</y></SimpleBean>", SimpleBean.class);
38+
assertTrue(value.getX() == 1 && value.getY() == 2);
39+
}
40+
@Test
41+
public void whenJavaGotFromXmlFile_thenCorrect() throws IOException {
42+
File file = new File("simple_bean.xml");
43+
XmlMapper xmlMapper = new XmlMapper();
44+
String xml = inputStreamToString(new FileInputStream(file));
45+
SimpleBean value = xmlMapper.readValue(xml,SimpleBean.class);
46+
assertTrue(value.getX() == 1 && value.getY() == 2);
47+
}
48+
49+
public static String inputStreamToString(InputStream is) throws IOException {
50+
BufferedReader br = null;
51+
StringBuilder sb = new StringBuilder();
52+
53+
String line;
54+
br = new BufferedReader(new InputStreamReader(is));
55+
while ((line = br.readLine()) != null) {
56+
sb.append(line);
57+
}
58+
br.close();
59+
return sb.toString();
60+
61+
}
62+
}
63+
64+
class SimpleBean {
65+
private int x = 1;
66+
private int y = 2;
67+
public int getX() {
68+
return x;
69+
}
70+
public void setX(int x) {
71+
this.x = x;
72+
}
73+
public int getY() {
74+
return y;
75+
}
76+
public void setY(int y) {
77+
this.y = y;
78+
}
79+
80+
}

0 commit comments

Comments
 (0)