简体   繁体   中英

Converting ArrayList to String and converted String back to ArrayList

I am in a situation where I need to send the arraylist in the network but I need to convert it in the form of string.

Now at the destination I want to convert this String to ArrayList to access the individual elements.

Please tell me how I can convert the converted String(from ArrayList) back to ArrayList.

ArrayList of what? If the elements are strings or integers - simply join them using some unique separator and split back to array on the other side.

If you want to send an ArrayList of arbitrary Serializable objects, you will have to serialize it, eg using Java serialization . However this will produce byte[] array rather than a String. If you are constrained to text protocol, you would then gonna have to use Base64 encoding or similar.

That depends on whether it is possible to provide an exact string representation of the objects in your array list.

The next question would be: why does it need to be a string represenation of the arraylist?

That said, if it really needs to be a string representation, JSON might help you, ie you convert the array list to a JSON represenation and back. There are a multitude of JSON frameworks out there like GSON, JSON-simple etc.

  private string ArrayListToString(System.Collections.ArrayList list)
        {
            string CStr = "";

            foreach (string str in list)
            {
                CStr += str;
                CStr += "<b>";
            }

            return CStr;
        }

        private System.Collections.ArrayList ArrayListToString(string CStr)
        {
            System.Collections.ArrayList list = new System.Collections.ArrayList();
            string[] seperator = { "<b>" };
            string[] words = CStr.Split(seperator, StringSplitOptions.RemoveEmptyEntries);

            foreach (string str in words)
            {
                list.Add(str);
            }

            return list;
        }

I would rather not use program language specified binary serialization. Will get stuck by some versioning problem future.

You can use JSON format, use JSONArray.toString and JSONArray.fromObject(String) for serial/deserial

If you need performance on speed and space,

I suggest Google Protocol Buffers , it is a way of encoding structured data in an efficient yet extensible format. Google uses Protocol Buffers for almost all of its internal RPC protocols and file formats.

Protocol buffers have many advantages over XML for serializing structured data. Protocol buffers:

* are simpler
* are 3 to 10 times smaller
* are 20 to 100 times faster
* are less ambiguous
* generate data access classes that are easier to use programmatically

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM