Serialize and Deserialize series of strings

Just a quick example of serializing and deserializing a series of strings.

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class GEncode {

	String serialize(List strings) throws UnsupportedEncodingException {
		String serialized = "";
		for (String s : strings) {
			serialized += URLEncoder.encode(s, "UTF-8") + "&";
		}
		return serialized;
	}

	@SuppressWarnings("deprecation")
	List deserialize(String serialized) {
		String[] strings = serialized.split("&");
		for (int i = 0; i < strings.length; i++) {
			strings[i] = URLDecoder.decode(strings[i]);
		}
		List list = Arrays.asList(strings);
		return list;
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		List strings = new LinkedList();
		strings.add("Old & New");
		strings.add("Once upon a time!");
		strings.add("Yes, there is a monster in the closet");
		strings.add("Another string? Why, I don't mind if I do!");
		strings.add("She said \"Yes\"");

		for (String s : strings) {
			System.out.println (s);
		}

		GEncode g = new GEncode();
		String s = g.serialize(strings);

		System.out.println ("\nSerialized:\n" + s + "\n\nDeserialized:");

		List newStrings = g.deserialize(s);

		int i = 1;
		for (String ns : newStrings) {
			System.out.println (i + ": " + ns);
			i++;
		}
	}
}

Output:

Old & New
Once upon a time!
Yes, there is a monster in the closet
Another string? Why, I don't mind if I do!
She said "Yes"

Serialized:
Old+%26+New&Once+upon+a+time%21&Yes%2C+there+is+a+monster+in+the+closet&Another+string%3F+Why%2C+I+don%27t+mind+if+I+do%21&She+said+%22Yes%22&

Deserialized:
1: Old & New
2: Once upon a time!
3: Yes, there is a monster in the closet
4: Another string? Why, I don't mind if I do!
5: She said "Yes"

One Response to “Serialize and Deserialize series of strings”

  1. Romain says:

    Thanks for this post, not something crazy but will be useful for me to simply store a list of string without making relative base in SQLite!

Leave a Reply

 

Staypressed theme by Themocracy