日期:2014-05-16 浏览次数:20481 次
先列出来正确的解析代码,接着再描述问题详情。
首先是用到的JavaBean
package com.jadyer.model; public class User { private String name; private Book book; public String getName() { return name; } public void setName(String name) { this.name = name; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } }
package com.jadyer.model; public class Book { private String name; // private List<Author> author = new ArrayList<Author>(); private Author author; public String getName() { return name; } public void setName(String name) { this.name = name; } // public List<Author> getAuthor() { // return author; // } // public void setAuthor(List<Author> author) { // this.author = author; // } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } }
package com.jadyer.model; public class Author { private String name; private int money; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } }
package com.jadyer.main; import java.io.IOException; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import com.alibaba.fastjson.JSON; import com.jadyer.model.User; public class JSONDemo { // /** // * 生成{"book":{"author":[{"money":500,"name":"南派三叔"},{"money":200,"name":"孔二狗"}],"name":"网络文学"},"name":"玄玉"} // */ // private static String format(){ // List<Author> authorList = new ArrayList<Author>(); // Author author11 = new Author(); // author11.setName("南派三叔"); // author11.setMoney(500); // authorList.add(author11); // Author author22 = new Author(); // author22.setName("孔二狗"); // author22.setMoney(200); // authorList.add(author22); // Book book = new Book(); // book.setName("网络文学"); // book.setAuthor(authorList); // User user = new User(); // user.setName("玄玉"); // user.setBook(book); // return JSON.toJSONString(user); // } public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { String jsonText = "{\"book\":{\"author\":{\"money\":500,\"name\":\"南派三叔\"},\"name\":\"网络文学\"},\"name\":\"玄玉\"}"; //用到的jar为fastjson-1.1.36.jar User userFromFastJSON = JSON.parseObject(jsonText, User.class); System.out.println(ReflectionToStringBuilder.toString(userFromFastJSON.getBook().getAuthor(), ToStringStyle.MULTI_LINE_STYLE)); System.out.pri