user3360031
user3360031

Reputation: 627

Convert String array to string back to string array

I converted a string array to string using Arrays.toString(variable) and saved it in a session. Now I want to convert it back to a string array. How do I do that?

I was hoping if there's a way to do it in a simpler way, like parsing it to string array.

Here's a sample of the string. It is separated by a comma.

[Any, Resolved (1), ANS MACH / LEFT MSG (1)]

Update:
I've been advised not to use toString to serialize array. But since I'm dealing with simple array, I still opted to use it.

Upvotes: 2

Views: 14145

Answers (4)

Pshemo
Pshemo

Reputation: 124215

Simplest solution (assuming that we are talking about Java EE's HttpSession) would be not placing String representing array, but array itself via setAttribute(String name, Object value) so as you see value can be any Object, not only String.

DEMO using List<String> instead of String[] (may not be perfect but should get the idea):

@WebServlet("/SessionDemo")
public class SessionDemo extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        List<String> list = (List<String>) session.getAttribute("list");

        printList(out, list);
        printForm(out);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();

        List<String> list = (List<String>) session.getAttribute("list");

        if (list == null){
            list = new ArrayList<>();
            session.setAttribute("list", list);
        }
        list.add(request.getParameter("item"));

        printList(out, list);
        printForm(out);

    }

    private void printList(PrintWriter out, List<String> list) {
        out.println("current items:");
        if (list != null){
            out.println("<ul>");
            for (String item : list){
                out.append("<li>").append(item).println("</li>");
            }
            out.println("</ul>");
        }else{
            out.println("list is empty");
        }
        out.println("<hr/>");
    }

    private void printForm(PrintWriter out){
        out.println(
                "<form action='./SessionDemo' method='post'>"
                + "<input type='text' name='item'/>"
                + "<input type='submit' value='add to list'/>"
                + "</form>"
        );
    }

}

Upvotes: 0

Manwal
Manwal

Reputation: 23816

If you always wants string operation with this kinda sting split() is what you need:

public static void main(String []args){
    String string = "[Any, Resolved (1), ANS MACH / LEFT MSG (1)]";
    String[] parts = string.split(",");// your string Array
    int i=0;

    for(; i< parts.length; i++)
        System.out.println(parts[i]);
 }

If your string contains [ and ] also. Then you would need .replace()


Best practice to use JSON for Response/Request processing.

Upvotes: -1

solar
solar

Reputation: 1364

I guess that's the answer you're searching for. Briefly, it's about using serialization with apache codecs for encoding/decoding objects. I don't want to do copy/paste from another answer, so I'll give you only the code sample in case link changes someday. Here it is:

  // serialize
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    new ObjectOutputStream(out).writeObject(yourArray);

 //encode
    String encodeString = new String(Hex.encodeHex(out.toByteArray()));

 // deserialize
    ByteArrayInputStream in = new ByteArrayInputStream(Hex.decodeHex(yourString.toCharArray()));
    String yourArray = Arrays.toString((String[]) new ObjectInputStream(in).readObject());
}
// And then you could use `String#split()` method to convert string to array.

Another option is to use something like Gson JSON library, with Gson, you can convert any java object to a json string and then convert it back. Example code may looks like this:

//Put an array (or any other object to gson object
Gson gson = new Gson();
String json = gson.toJson(yourArray);

// Retrieve your object from gson
Gson gson = new Gson();
Array array = gson.fromJson(json, Array.class);

For more details you look this article.

Upvotes: 1

Andy Thomas
Andy Thomas

Reputation: 86381

If the individual strings might themselves include a comma followed by a space, then this would not be feasible. Multiple String[] arrays could map to the same flat String, and an inverse function would not exist.

However, you note in a comment that your strings cannot include the comma separator. You can split the flat string back into the original substrings, using ", " (comma,space) as a separator.

APIs that support this include the standard Java String.split() method, and Guava's Splitter class.

Here's an example with Java's split() method:

public static void main(String[] args) {
    String[] strs = new String[] { "Foo", "Bar", "Baz" };

    String joined = Arrays.toString( strs );

    String joinedMinusBrackets = joined.substring( 1, joined.length() - 1);

    // String.split()
    String[] resplit = joinedMinusBrackets.split( ", "); 

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

}

And here's an example with Guava's Splitter class:

public static void main(String[] args) {
    String[] strs = new String[] { "Foo", "Bar", "Baz" };

    String joined = Arrays.toString( strs );

    String joinedMinusBrackets = joined.substring( 1, joined.length() - 1);

    // Guava Splitter class
    List<String> resplitList = Splitter.on( ", " ).splitToList( joinedMinusBrackets );

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

Upvotes: 3

Related Questions