当前位置: 代码迷 >> JavaScript >> Jackson的对象与json其间的转换
  详细解决方案

Jackson的对象与json其间的转换

热度:255   发布时间:2012-08-21 13:00:21.0
Jackson的对象与json之间的转换
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		sb.append("\"name\" : { \"first\" : \"Joe\", \"last\" : \"Sixpack\" },");
		sb.append("\"gender\" : \"MALE\",");
		sb.append("\"verified\" : false,");
		sb.append("\"userImage\" : \"Rm9vYmFyIQ==\"");
		sb.append("}");
		
		ObjectMapper mapper = new ObjectMapper();
		User user = mapper.readValue(sb.toString(), User.class);
		
		ObjectMapper mapper2 = new ObjectMapper();  
		StringWriter sw = new StringWriter();  
		JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);  
		mapper2.writeValue(gen, user);  
		gen.close();  
		String json = sw.toString();
		System.out.println(json);User类
public class User {
	
	public enum Gender {
		MALE, FEMALE
	};

	public static class Name {
		private String _first, _last;

		public String getFirst() {
			return _first;
		}

		public String getLast() {
			return _last;
		}

		public void setFirst(String s) {
			_first = s;
		}

		public void setLast(String s) {
			_last = s;
		}
	}

	private Gender _gender;
	private Name _name;
	private boolean _isVerified;
	private byte[] _userImage;

	public Name getName() {
		return _name;
	}

	public boolean isVerified() {
		return _isVerified;
	}

	public Gender getGender() {
		return _gender;
	}

	public byte[] getUserImage() {
		return _userImage;
	}

	public void setName(Name n) {
		_name = n;
	}

	public void setVerified(boolean b) {
		_isVerified = b;
	}

	public void setGender(Gender g) {
		_gender = g;
	}

	public void setUserImage(byte[] b) {
		_userImage = b;
	}
}
?
  相关解决方案