Android Object Serialization stringToObject(String s)

Here you can find the source of stringToObject(String s)

Description

string To Object

Declaration

public static Object stringToObject(String s) 

Method Source Code

//package com.java2s;
import java.io.BufferedInputStream;

import java.io.ByteArrayInputStream;

import java.io.ObjectInputStream;

public class Main {
    public static Object stringToObject(String s) {
        if (s == null) {
            return null;
        }/*from ww  w. j av  a 2s. c om*/

        byte byteArray[] = decode(s);

        ByteArrayInputStream baos = new ByteArrayInputStream(byteArray);

        try {
            ObjectInputStream is = new ObjectInputStream(
                    new BufferedInputStream(baos));

            return is.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static byte[] decode(String base64) {
        int pad = 0;

        for (int i = base64.length() - 1; base64.charAt(i) == '='; i--) {
            pad++;
        }

        int length = (base64.length() * 6) / 8 - pad;
        byte raw[] = new byte[length];
        int rawindex = 0;

        for (int i = 0; i < base64.length(); i += 4) {
            int block = (getValue(base64.charAt(i)) << 18)
                    + (getValue(base64.charAt(i + 1)) << 12)
                    + (getValue(base64.charAt(i + 2)) << 6)
                    + getValue(base64.charAt(i + 3));

            for (int j = 0; j < 3 && rawindex + j < raw.length; j++) {
                raw[rawindex + j] = (byte) (block >> 8 * (2 - j) & 0xff);
            }

            rawindex += 3;
        }

        return raw;
    }

    protected static int getValue(char c) {
        if (c >= 'A' && c <= 'Z') {
            return c - 65;
        }

        if (c >= 'a' && c <= 'z') {
            return (c - 97) + 26;
        }

        if (c >= '0' && c <= '9') {
            return (c - 48) + 52;
        }

        if (c == '+') {
            return 62;
        }

        if (c == '/') {
            return 63;
        }

        return c != '=' ? -1 : 0;
    }
}

Related

  1. readObjectFromFile(String filename)
  2. saveObjectAsFile(String filename, Object object)
  3. writeObjectToFile(File fileLocation, Object obj)
  4. writeObjectToFile(Serializable obj, String filename)
  5. objectToString(Object o)
  6. getBytes(Serializable obj)
  7. deserialize(final File file, final long serialTtl)
  8. serialize(final File file, final Object o)
  9. saveObject(Context context, String fileName, Object obj)