まめーじぇんと@Tech

技術ネタに関して (Android, GAE, Angular). Twitter: @mame01122

GAE上でString→Blob、Blob→Stringの変換

GAEでAndroidから渡されたStirngをBlobにしてDatastoreに格納したい、
というケースがあったのでメモ。

■StringからBlob

String origin = "test string";
if (origin != null) {
	try {
		byte[] bytes = origin.getBytes("UTF-8");
		return new Blob(bytes);
	} catch (UnsupportedEncodingException e) {
		log.log(Level.WARNING,
				"UnsupportedEncodingException: " + e.getMessage());
	}
}

■BlobからString

Blob origin = (Datastoreなどから引っ張ってきたBlobデータ)
if (origin != null) {
	byte[] bytes = origin.getBytes();
	if (bytes != null) {
		try {
			return new String(bytes, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			log.log(Level.WARNING,
					"UnsupportedEncodingException: " + e.getMessage());
		}
	}
}

これでできるハズ。