用Gson解析json数据代码段

public void parseUserFromJson(){
		String jsonData = "{\"name\":\"Michael\",\"age\":20}";
		Gson gson = new Gson();
		//User是bean类
		User user = gson.fromJson(jsonData, User.class);
		System.out.println("name--->" + user.getName());
		System.out.println("age---->" + user.getAge());
		
	}

Json数组

public void parseUserFromJson(){
		String jsonData = "[{\"name\":\"Michael\",\"age\":20},{\"name\":\"Mike\",\"age\":21}]";
		Type listType = new TypeToken<LinkedList<User>>(){}.getType();
		Gson gson = new Gson();
		LinkedList<User> users = gson.fromJson(jsonData, listType);
		for (Iterator iterator = users.iterator(); iterator.hasNext();) {
			User user = (User) iterator.next();
			System.out.println("name--->" + user.getName());
			System.out.println("age---->" + user.getAge());
		}
		
	}


你可能感兴趣的:(用Gson解析json数据代码段)