-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSolution.java
More file actions
73 lines (51 loc) · 2.8 KB
/
Solution.java
File metadata and controls
73 lines (51 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//And I saw a great white throne, and him that sat on it, from whose face the earth and the heaven fled away; and there was found no place for them. (Revelation 20:11)
package com.javarush.task.task33.task3307;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.IOException;
import java.io.StringReader;
/*
Десериализация XML объекта
*/
public class Solution {
public static void main(String[] args) throws IOException, JAXBException {
String xmlData = "<cat><name>Murka</name><age>5</age><weight>4</weight></cat>";
Cat cat = convertFromXmlToNormal(xmlData, Cat.class);
System.out.println(cat);
}
public static <T> T convertFromXmlToNormal(String xmlData, Class<T> clazz) throws IOException, JAXBException {
StringReader reader = new StringReader(xmlData);
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
return (T) unmarshaller.unmarshal(reader);
}
@XmlType(name = "cat")
@XmlRootElement
public static class Cat {
public String name;
public int age;
public int weight;
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
", age=" + age +
", weight=" + weight +
'}';
}
}
}
/*
Десериализация XML объекта
В метод convertFromXmlToNormal первым параметром приходит строка, содержащая xml объект.
Вторым параметром приходит класс, объект которого необходимо вернуть.
Метод convertFromXmlToNormal должен создать объект из xml-строки и вернуть его.
Требования:
1. В методе convertFromXmlToNormal должен быть создан новый объект типа JAXBContext с помощью статического метода JAXBContext.newInstance, в качестве параметра используй целевой класс.
2. В методе convertFromXmlToNormal должен быть создан новый объект типа Unmarshaller с помощью метода createUnmarshaller вызванного на объекте типа JAXBContext.
3. Метод convertFromXmlToNormal должен корректно преобразовывать входящую xml строку в объект требуемого класса.
4. Метод convertFromXmlToNormal должен быть статическим.
*/