现在的位置: 首页 > 综合 > 正文

JSON解析

2018年04月05日 ⁄ 综合 ⁄ 共 878字 ⁄ 字号 评论关闭
	
	/**
	 * {"books":[{"bookName":"围城","author":"钱钟书"},{"bookName":"西游记","author":"吴承恩"}]}
	 *
	 */
	class Book{
		public String bookName;
		public String author;
		public String getBookName() {
			return bookName;
		}
		public void setBookName(String bookName) {
			this.bookName = bookName;
		}
		public String getAuthor() {
			return author;
		}
		public void setAuthor(String author) {
			this.author = author;
		}
	}
	
	public List<Book> getBooks(String json){
		List list = new ArrayList<Book>();
		try { 			
			if (json != null && json.length() > 0) {
				
				try {
					JSONObject jsonObject = new JSONObject(json);
					JSONArray jsonArray = jsonObject.getJSONArray("books");
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
						Book b = new Book();
						String name = jsonObject2.getString("bookName");
						String author = jsonObject2.getString("author");
						b.setBookName(name);
						b.setAuthor(author);
						list.add(b);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
	}catch(Exception ex) {
		ex.printStackTrace() ;
	} 
		return list;
	}

抱歉!评论已关闭.