상세 컨텐츠

본문 제목

Hibernate Validator 사용 , jdom , json 사용

개발

by 동동주1123 2011. 10. 16. 14:51

본문

SAXBuilder saxBuilder = new SAXBuilder(true);

// Document doc = saxBuilder.build(instream);
// Element root = doc.getRootElement();
// List list = root.getChildren("item");

saxBuilder.setValidation(false);
Document document = saxBuilder.build(new StringReader(result));
// Document document = saxBuilder.build(instream);
System.out.println(document);
Element rootNode = document.getRootElement();
List list = rootNode.getChild("channel").getChildren("item");

// JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();

// List<Map> mapParent = new ArrayList<Map>();

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();

List<Book> bookList = new ArrayList<Book>();

for (int i = 0; i < list.size(); i++) {
Element node = (Element) list.get(i);

Book book = new Book();

book.setTitle(node.getChildText("title"));
book.setAuthor(node.getChildText("author"));
book.setLink(node.getChildText("link"));
book.setPrice(Integer.parseInt(node.getChildText("price")));
book.setPublisher(node.getChildText("publisher"));

Set<ConstraintViolation<Book>> violations = validator.validate(book);
System.out.println(violations);
if( violations.size() > 0 ) throw new ValidationException();
bookList.add(book);

// Map<String , String> mapSub = new HashMap<String ,
// String>();
//
// mapSub.put("title", node.getChildText("title"));
// mapSub.put("link", node.getChildText("link"));
// mapSub.put("author", node.getChildText("author"));
// mapSub.put("price", node.getChildText("price"));
// mapSub.put("publisher",node.getChildText("publisher"));
//
// mapParent.add(mapSub);



System.out.println(jsonObject.put("book", bookList)); 





Model 객체(도메인 클래스)



import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

public class Book {
@NotNull
String title;

@NotNull
String link;

@NotNull
String author;

@NotNull
@Max(1000)
int price;

String publisher;

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getLink() {
return link;
}

public void setLink(String link) {
this.link = link;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public int getPrice() {
return price;
}

public void setPrice(int price) {
this.price = price;
}

public String getPublisher() {
return publisher;
}

public void setPublisher(String publisher) {
this.publisher = publisher;
}

}

 

관련글 더보기