`
mengdejun
  • 浏览: 408713 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

javascript实现序列化serializable unserializable

    博客分类:
  • JS
阅读更多
/* phpserializer.js - JavaScript to PHP serialize / unserialize class. 
*  
* This class is designed to convert php variables to javascript 
* and javascript variables to php with a php serialize unserialize 
* compatible way. 
* 
* Copyright (C) 2006 Ma Bingyao <andot@ujn.edu.cn> 
* Version: 3.0c 
* LastModified: Jun 2, 2006 
* This library is free.  You can redistribute it and/or modify it. 
* http://www.coolcode.cn/?p=171 
*/ 
  
function serialize(o) { 
    var p = 0, sb = [], ht = [], hv = 1; 
    function classname(o) { 
        if (typeof(o) == "undefined" || typeof(o.constructor) == "undefined") return ''; 
        var c = o.constructor.toString(); 
        c = utf16to8(c.substr(0, c.indexOf('(')).replace(/(^\s*function\s*)|(\s*$)/ig, '')); 
        return ((c == '') ? 'Object' : c); 
    } 
    function is_int(n) { 
        var s = n.toString(), l = s.length; 
        if (l > 11) return false; 
        for (var i = (s.charAt(0) == '-') ? 1 : 0; i < l; i++) { 
            switch (s.charAt(i)) { 
                case '0': 
                case '1': 
                case '2': 
                case '3': 
                case '4': 
                case '5': 
                case '6': 
                case '7': 
                case '8': 
                case '9': break; 
                default : return false; 
            } 
        } 
        return !(n < -2147483648 || n > 2147483647); 
    } 
    function in_ht(o) { 
        for (k in ht) if (ht[k] === o) return k; 
        return false; 
    } 
    function ser_null() { 
        sb[p++] = 'N;'; 
    } 
    function ser_boolean(b) { 
        sb[p++] = (b ? 'b:1;' : 'b:0;'); 
    } 
    function ser_integer(i) { 
        sb[p++] = 'i:' + i + ';'; 
    } 
    function ser_double(d) { 
        if (d == Number.POSITIVE_INFINITY) d = 'INF'; 
        else if (d == Number.NEGATIVE_INFINITY) d = '-INF'; 
        sb[p++] = 'd:' + d + ';'; 
    } 
    function ser_string(s) { 
        var utf8 = utf16to8(s); 
        sb[p++] = 's:' + utf8.length + ':"'; 
        sb[p++] = utf8; 
        sb[p++] = '";'; 
    } 
    function ser_array(a) { 
        sb[p++] = 'a:'; 
        var lp = p; 
        sb[p++] = 0; 
        sb[p++] = ':{'; 
        for (var k in a) { 
            if (typeof(a[k]) != 'function') { 
                is_int(k) ? ser_integer(k) : ser_string(k); 
                __serialize(a[k]); 
                sb[lp]++; 
            } 
        } 
        sb[p++] = '}'; 
    } 
    function ser_object(o) { 
        var cn = classname(o); 
        if (cn == '') ser_null(); 
        else if (typeof(o.serialize) != 'function') { 
            sb[p++] = 'O:' + cn.length + ':"'; 
            sb[p++] = cn; 
            sb[p++] = '":'; 
            var lp = p; 
            sb[p++] = 0; 
            sb[p++] = ':{'; 
            if (typeof(o.__sleep) == 'function') { 
                var a = o.__sleep(); 
                for (var kk in a) { 
                    ser_string(a[kk]); 
                    __serialize(o[a[kk]]); 
                    sb[lp]++; 
                } 
            } 
            else { 
                for (var k in o) { 
                    if (typeof(o[k]) != 'function') { 
                        ser_string(k); 
                        __serialize(o[k]); 
                        sb[lp]++; 
                    } 
                } 
            } 
            sb[p++] = '}'; 
        } 
        else { 
            var cs = o.serialize(); 
            sb[p++] = 'C:' + cn.length + ':"'; 
            sb[p++] = cn; 
            sb[p++] = '":' + cs.length + ':{'; 
            sb[p++] = cs; 
            sb[p++] = "}"; 
        } 
    } 
    function ser_pointref(R) { 
        sb[p++] = "R:" + R + ";"; 
    } 
    function ser_ref(r) { 
        sb[p++] = "r:" + r + ";"; 
    } 
    function __serialize(o) { 
        if (o == null || o.constructor == Function) { 
            hv++; 
            ser_null(); 
        } 
        else switch (o.constructor) { 
            case Boolean: { 
                hv++; 
                ser_boolean(o); 
                break; 
            } 
            case Number: { 
                hv++; 
                is_int(o) ? ser_integer(o) : ser_double(o); 
                break; 
            } 
            case String: { 
                hv++; 
                ser_string(o); 
                break; 
            } 
            case Array: { 
                var r = in_ht(o); 
                if (r) { 
                    ser_pointref(r); 
                } 
                else { 
                    ht[hv++] = o; 
                    ser_array(o); 
                } 
                break; 
            } 
            default: { 
                var r = in_ht(o); 
                if (r) { 
                    hv++; 
                    ser_ref(r); 
                } 
                else { 
                    ht[hv++] = o; 
                    ser_object(o); 
                } 
                break; 
            } 
        } 
    } 
    __serialize(o); 
    return sb.join(''); 
} 
  
function unserialize(ss) { 
    var p = 0, ht = [], hv = 1; r = null; 
    function unser_null() { 
        p++; 
        return null; 
    } 
    function unser_boolean() { 
        p++; 
        var b = (ss.charAt(p++) == '1'); 
        p++; 
        return b; 
    } 
    function unser_integer() { 
        p++; 
        var i = parseInt(ss.substring(p, p = ss.indexOf(';', p))); 
        p++; 
        return i; 
    } 
    function unser_double() { 
        p++; 
        var d = ss.substring(p, p = ss.indexOf(';', p)); 
        switch (d) { 
            case 'INF': d = Number.POSITIVE_INFINITY; break; 
            case '-INF': d = Number.NEGATIVE_INFINITY; break; 
            default: d = parseFloat(d); 
        } 
        p++; 
        return d; 
    } 
    function unser_string() { 
        p++; 
        var l = parseInt(ss.substring(p, p = ss.indexOf(':', p))); 
        p += 2; 
        var s = utf8to16(ss.substring(p, p += l)); 
        p += 2; 
        return s; 
    } 
    function unser_array() { 
        p++; 
        var n = parseInt(ss.substring(p, p = ss.indexOf(':', p))); 
        p += 2; 
        var a = []; 
        ht[hv++] = a; 
        for (var i = 0; i < n; i++) { 
            var k; 
            switch (ss.charAt(p++)) { 
                case 'i': k = unser_integer(); break; 
                case 's': k = unser_string(); break; 
                case 'U': k = unser_unicode_string(); break; 
                default: return false; 
            } 
            a[k] = __unserialize(); 
        } 
        p++; 
        return a; 
    } 
    function unser_object() { 
        p++; 
        var l = parseInt(ss.substring(p, p = ss.indexOf(':', p))); 
        p += 2; 
        var cn = utf8to16(ss.substring(p, p += l)); 
        p += 2; 
        var n = parseInt(ss.substring(p, p = ss.indexOf(':', p))); 
        p += 2; 
        if (eval(['typeof(', cn, ') == "undefined"'].join(''))) { 
            eval(['function ', cn, '(){}'].join('')); 
        } 
        var o = eval(['new ', cn, '()'].join('')); 
        ht[hv++] = o; 
        for (var i = 0; i < n; i++) { 
            var k; 
            switch (ss.charAt(p++)) { 
                case 's': k = unser_string(); break; 
                case 'U': k = unser_unicode_string(); break; 
                default: return false; 
            } 
            if (k.charAt(0) == '\0') { 
                k = k.substring(k.indexOf('\0', 1) + 1, k.length); 
            } 
            o[k] = __unserialize(); 
        } 
        p++; 
        if (typeof(o.__wakeup) == 'function') o.__wakeup(); 
        return o; 
    } 
    function unser_custom_object() { 
        p++; 
        var l = parseInt(ss.substring(p, p = ss.indexOf(':', p))); 
        p += 2; 
        var cn = utf8to16(ss.substring(p, p += l)); 
        p += 2; 
        var n = parseInt(ss.substring(p, p = ss.indexOf(':', p))); 
        p += 2; 
        if (eval(['typeof(', cn, ') == "undefined"'].join(''))) { 
            eval(['function ', cn, '(){}'].join('')); 
        } 
        var o = eval(['new ', cn, '()'].join('')); 
        ht[hv++] = o; 
        if (typeof(o.unserialize) != 'function') p += n; 
        else o.unserialize(ss.substring(p, p += n)); 
        p++; 
        return o; 
    } 
    function unser_unicode_string() { 
        p++; 
        var l = parseInt(ss.substring(p, p = ss.indexOf(':', p))); 
        p += 2; 
        var sb = []; 
        for (i = 0; i < l; i++) { 
            if ((sb[i] = ss.charAt(p++)) == '\\') { 
                sb[i] = String.fromCharCode(parseInt(ss.substring(p, p += 4), 16)); 
            } 
        } 
        p += 2; 
        return sb.join(''); 
    } 
    function unser_ref() { 
        p++; 
        var r = parseInt(ss.substring(p, p = ss.indexOf(';', p))); 
        p++; 
        return ht[r]; 
    } 
    function __unserialize() { 
        switch (ss.charAt(p++)) { 
            case 'N': return ht[hv++] = unser_null(); 
            case 'b': return ht[hv++] = unser_boolean(); 
            case 'i': return ht[hv++] = unser_integer(); 
            case 'd': return ht[hv++] = unser_double(); 
            case 's': return ht[hv++] = unser_string(); 
            case 'U': return ht[hv++] = unser_unicode_string(); 
            case 'r': return ht[hv++] = unser_ref(); 
            case 'a': return unser_array(); 
            case 'O': return unser_object(); 
            case 'C': return unser_custom_object(); 
            case 'R': return unser_ref(); 
            default: return false; 
        } 
    } 
    return __unserialize(); 
}

 

/* utf.js - UTF-8 <=> UTF-16 convertion
*
* Copyright (C) 2010 zys <zys-101@163.com>
* Version: 1.0
* LastModified: Six 3, 2010
* This library is free.  You can redistribute it and/or modify it.
*/

/*
* Interfaces:
* utf8 = utf16to8(utf16);
* utf16 = utf16to8(utf8);
*/

function utf16to8(str) {
var out, i, len, c;

out = "";
len = str.length;
for(i = 0; i < len; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
out += str.charAt(i);
} else if (c > 0x07FF) {
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
}
}
return out;
}

function utf8to16(str) {
var out, i, len, c;
var char2, char3;

out = "";
len = str.length;
i = 0;
while(i < len) {
c = str.charCodeAt(i++);
switch(c >> 4)
{ 
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
// 0xxxxxxx
out += str.charAt(i-1);
break;
case 12: case 13:
// 110x xxxx   10xx xxxx
char2 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
// 1110 xxxx  10xx xxxx  10xx xxxx
char2 = str.charCodeAt(i++);
char3 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
break;
}
}

return out;
}

 

<html>
<head>
<title>Test</title>
<script type="text/javascript" src="./utf.js"></script>
<script type="text/javascript" src="./phpserializer.js"></script>
</head>
<body>
<script type="text/javascript">
function test()
{
	var arr = new Array(1,2,3);
	var arr2 = new Array('a','b','c');
	arr['test'] = arr2; 
	var obj={x:arr};
	var str = serialize(obj);
	alert(str);
}
test();
</script>
</body>
</html>

 

/**
 * Object PHP_Serializer
 * 	JavaScript to PHP serialize / unserialize class.
 * This class converts php variables to javascript and vice versa.
 *
 * PARSABLE JAVASCRIPT < === > PHP VARIABLES:
 *	[ JAVASCRIPT TYPE ]		[ PHP TYPE ]
 *	Array		< === > 	array
 *	Object		< === > 	class (*)
 *	String		< === > 	string
 *	Boolean		< === > 	boolean
 *	null		< === > 	null
 *	Number		< === > 	int or double
 *	Date		< === > 	class
 *	Error		< === > 	class
 *	Function	< === > 	class (*)
 *
 * (*) NOTE:
 * Any PHP serialized class requires the native PHP class to be used, then it's not a
 * PHP => JavaScript converter, it's just a usefull serilizer class for each
 * compatible JS and PHP variable types.
 * Lambda, Resources or other dedicated PHP variables are not usefull for JavaScript.
 * There are same restrictions for javascript functions*** too then these will not be sent.
 *
 * *** function test(); alert(php.serialize(test)); will be empty string but
 * *** mytest = new test(); will be sent as test class to php
 * _____________________________________________
 *
 * EXAMPLE:
 *	var php = new PHP_Serializer(); // use new PHP_Serializer(true); to enable UTF8 compatibility
 *	alert(php.unserialize(php.serialize(somevar)));
 *	// should alert the original value of somevar
 * ---------------------------------------------
 * @author              Andrea Giammarchi
 * @site		www.devpro.it
 * @date                2005/11/26
 * @lastmod             2006/05/15 19:00 [modified stringBytes method and removed replace for UTF8 and \r\n]
 * 			[add UTF8 var again, PHP strings if are not encoded with utf8_encode aren't compatible with this object]
 *			[Partially rewrote for a better stability and compatibility with Safari or KDE based browsers]
 *			[UTF-8 now has a native support, strings are converted automatically with ISO or UTF-8 charset]
 *
 * @specialthanks	Fabio Sutto, Kentaromiura, Kroc Camen, Cecile Maigrot, John C.Scott, Matteo Galli
 *
 * @version             2.2, tested on FF 1.0, 1.5, IE 5, 5.5, 6, 7 beta 2, Opera 8.5, Konqueror 3.5, Safari 2.0.3
 */
function PHP_Serializer(UTF8) {
	
	/** public methods */
	function serialize(v) {
		// returns serialized var
		var	s;
		switch(v) {
			case null:
				s = "N;";
				break;
			default:
				s = this[this.__sc2s(v)] ? this[this.__sc2s(v)](v) : this[this.__sc2s(__o)](v);
				break;
		};
		return s;
	};
	
	function unserialize(s) {
		// returns unserialized var from a php serialized string
		__c = 0;
		__s = s;
		return this[__s.substr(__c, 1)]();
	};
	
	function stringBytes(s) {
		// returns the php lenght of a string (chars, not bytes)
		return s.length;
	};
	
	function stringBytesUTF8(s) {
		// returns the php lenght of a string (bytes, not chars)
		var 	c, b = 0,
			l = s.length;
		while(l) {
			c = s.charCodeAt(--l);
			b += (c < 128) ? 1 : ((c < 2048) ? 2 : ((c < 65536) ? 3 : 4));
		};
		return b;
	};
	
	/** private methods */
	function __sc2s(v) {
		return v.constructor.toString();
	};
	
	function __sc2sKonqueror(v) {
		var	f;
		switch(typeof(v)) {
			case ("string" || v instanceof String):
				f = "__sString";
				break;
			case ("number" || v instanceof Number):
				f = "__sNumber";
				break;
			case ("boolean" || v instanceof Boolean):
				f = "__sBoolean";
				break;
			case ("function" || v instanceof Function):
				f = "__sFunction";
				break;
			default:
				f = (v instanceof Array) ? "__sArray" : "__sObject";
				break;
		};
		return f;
	};
	
	function __sNConstructor(c) {
		return (c === "[function]" || c === "(Internal Function)");
	};
	
	function __sCommonAO(v) {
		var	b, n,
			a = 0,
			s = [];
		for(b in v) {
			n = v[b] == null;
			if(n || v[b].constructor != Function) {
				s[a] = [
					(!isNaN(b) && parseInt(b).toString() === b ? this.__sNumber(b) : this.__sString(b)),
					(n ? "N;" : this[this.__sc2s(v[b])] ? this[this.__sc2s(v[b])](v[b]) : this[this.__sc2s(__o)](v[b]))
				].join("");
				++a;
			};
		};
		return [a, s.join("")];
	};
	
	function __sBoolean(v) {
		return ["b:", (v ? "1" : "0"), ";"].join("");
	};
	
	function __sNumber(v) {
		var 	s = v.toString();
		return (s.indexOf(".") < 0 ? ["i:", s, ";"] : ["d:", s, ";"]).join("");
	};
	
	function __sString(v) {
		return ["s:", v.length, ":\"", v, "\";"].join("");
	};
	
	function __sStringUTF8(v) {
		return ["s:", this.stringBytes(v), ":\"", v, "\";"].join("");
	};
	
	function __sArray(v) {
		var 	s = this.__sCommonAO(v);
		return ["a:", s[0], ":{", s[1], "}"].join("");
	};
	
	function __sObject(v) {
		var 	o = this.__sc2s(v),
			n = o.substr(__n, (o.indexOf("(") - __n)),
			s = this.__sCommonAO(v);
		return ["O:", this.stringBytes(n), ":\"", n, "\":", s[0], ":{", s[1], "}"].join("");
	};
	
	function __sObjectIE7(v) {
		var 	o = this.__sc2s(v),
			n = o.substr(__n, (o.indexOf("(") - __n)),
			s = this.__sCommonAO(v);
		if(n.charAt(0) === " ")
			n = n.substring(1);
		return ["O:", this.stringBytes(n), ":\"", n, "\":", s[0], ":{", s[1], "}"].join("");
	};
	
	function __sObjectKonqueror(v) {
		var	o = v.constructor.toString(),
			n = this.__sNConstructor(o) ? "Object" : o.substr(__n, (o.indexOf("(") - __n)),
			s = this.__sCommonAO(v);
		return ["O:", this.stringBytes(n), ":\"", n, "\":", s[0], ":{", s[1], "}"].join("");
	};
	
	function __sFunction(v) {
		return "";
	};
	
	function __uCommonAO(tmp) {
		var	a, k;
		++__c;
		a = __s.indexOf(":", ++__c);
		k = parseInt(__s.substr(__c, (a - __c))) + 1;
		__c = a + 2;
		while(--k)
			tmp[this[__s.substr(__c, 1)]()] = this[__s.substr(__c, 1)]();
		return tmp;
	};

	function __uBoolean() {
		var	b = __s.substr((__c + 2), 1) === "1" ? true : false;
		__c += 4;
		return b;
	};
	
	function __uNumber() {
		var	sli = __s.indexOf(";", (__c + 1)) - 2,
			n = Number(__s.substr((__c + 2), (sli - __c)));
		__c = sli + 3;
		return n;
	};
	
	function __uStringUTF8() {
		var 	c, sls, sli, vls,
			pos = 0;
		__c += 2;
		sls = __s.substr(__c, (__s.indexOf(":", __c) - __c));
		sli = parseInt(sls);
		vls = sls = __c + sls.length + 2;
		while(sli) {
			c = __s.charCodeAt(vls);
			pos += (c < 128) ? 1 : ((c < 2048) ? 2 : ((c < 65536) ? 3 : 4));
			++vls;
			if(pos === sli)
				sli = 0;
		};
		pos = (vls - sls);
		__c = sls + pos + 2;
		return __s.substr(sls, pos);
	};
	
	function __uString() {
		var 	sls, sli;
		__c += 2;
		sls = __s.substr(__c, (__s.indexOf(":", __c) - __c));
		sli = parseInt(sls);
		sls = __c + sls.length + 2;
		__c = sls + sli + 2;
		return __s.substr(sls, sli);
	};
	
	function __uArray() {
		var	a = this.__uCommonAO([]);
		++__c;
		return a;
	};
	
	function __uObject() {
		var 	tmp = ["s", __s.substr(++__c, (__s.indexOf(":", (__c + 3)) - __c))].join(""),
			a = tmp.indexOf("\""),
			l = tmp.length - 2,
			o = tmp.substr((a + 1), (l - a));
		if(eval(["typeof(", o, ") === 'undefined'"].join("")))
			eval(["function ", o, "(){};"].join(""));
		__c += l;
		eval(["tmp = this.__uCommonAO(new ", o, "());"].join(""));
		++__c;
		return tmp;
	};
	
	function __uNull() {
		__c += 2;
		return null;
	};
	
	function __constructorCutLength() {
		function ie7bugCheck(){};
		var	o1 = new ie7bugCheck(),
			o2 = new Object(),
			c1 = __sc2s(o1),
			c2 = __sc2s(o2);
		if(c1.charAt(0) !== c2.charAt(0))
			__ie7 = true;
		return (__ie7 || c2.indexOf("(") !== 16) ? 9 : 10;
	};
	
	/** private variables */
	var 	__c = 0,
		__ie7 = false,
		__b = __sNConstructor(__c.constructor.toString()),
		__n = __b ? 9 : __constructorCutLength(),
		__s = "",
		__a = [],
		__o = {},
		__f = function(){};
	
	/** public prototypes */
	PHP_Serializer.prototype.serialize = serialize;
	PHP_Serializer.prototype.unserialize = unserialize;
	PHP_Serializer.prototype.stringBytes = UTF8 ? stringBytesUTF8 : stringBytes;
	
	/** serialize: private prototypes */
	if(__b) { // Konqueror / Safari prototypes
		PHP_Serializer.prototype.__sc2s = __sc2sKonqueror;
		PHP_Serializer.prototype.__sNConstructor = __sNConstructor;
		PHP_Serializer.prototype.__sCommonAO = __sCommonAO;
		PHP_Serializer.prototype[__sc2sKonqueror(__b)] = __sBoolean;
		PHP_Serializer.prototype.__sNumber = 
		PHP_Serializer.prototype[__sc2sKonqueror(__n)] = __sNumber;
		PHP_Serializer.prototype.__sString = PHP_Serializer.prototype[__sc2sKonqueror(__s)] = UTF8 ? __sStringUTF8 : __sString;
		PHP_Serializer.prototype[__sc2sKonqueror(__a)] = __sArray;
		PHP_Serializer.prototype[__sc2sKonqueror(__o)] = __sObjectKonqueror;
		PHP_Serializer.prototype[__sc2sKonqueror(__f)] = __sFunction;
	}
	else { // FireFox, IE, Opera prototypes
		PHP_Serializer.prototype.__sc2s = __sc2s;
		PHP_Serializer.prototype.__sCommonAO = __sCommonAO;
		PHP_Serializer.prototype[__sc2s(__b)] = __sBoolean;
		PHP_Serializer.prototype.__sNumber = 
		PHP_Serializer.prototype[__sc2s(__n)] = __sNumber;
		PHP_Serializer.prototype.__sString = PHP_Serializer.prototype[__sc2s(__s)] = UTF8 ? __sStringUTF8 : __sString;
		PHP_Serializer.prototype[__sc2s(__a)] = __sArray;
		PHP_Serializer.prototype[__sc2s(__o)] = __ie7 ? __sObjectIE7 : __sObject;
		PHP_Serializer.prototype[__sc2s(__f)] = __sFunction;
	};
	
	/** unserialize: private prototypes */
	PHP_Serializer.prototype.__uCommonAO = __uCommonAO;
	PHP_Serializer.prototype.b = __uBoolean;
	PHP_Serializer.prototype.i =
	PHP_Serializer.prototype.d = __uNumber;
	PHP_Serializer.prototype.s = UTF8 ? __uStringUTF8 : __uString;
	PHP_Serializer.prototype.a = __uArray;
	PHP_Serializer.prototype.O = __uObject;
	PHP_Serializer.prototype.N = __uNull;
};

 

 

  • 大小: 4.8 KB
分享到:
评论

相关推荐

    java序列化(Serializable)的作用和反序列化.doc

    当对一个对象实现序列化时,具体会发生以下过程: 1. **对象状态的保存**:序列化会保存对象的所有实例变量的状态,但不会包括任何方法或静态变量。例如,对于一个`Box`对象,如果它有`width`和`height`两个实例...

    序列化 serializable demo

    首先,`Serializable`接口是Java中用于实现序列化的标志接口。它没有定义任何方法,但当一个类实现了这个接口,Java的ObjectOutputStream就可以将该类的对象写入到流中。例如,`MySerializable.java`和`Product.java...

    java序列化(Serializable)的作用和反序列化

    #### 四、实现序列化的步骤 序列化的过程可以分为几个简单的步骤: 1. **创建文件输出流(FileOutputStream)**:首先需要创建一个指向序列化文件的输出流。 ```java FileOutputStream fs = new FileOutputStream...

    java serializable 序列化与反序列化

    3. **如何实现序列化**:只需让类实现`Serializable`接口,Java的默认序列化机制就会处理剩余部分。例如: ```java public class MyObject implements Serializable { private String name; private int age; ...

    Android序列化——Serializable与Parcelable

    只需让类实现Serializable接口,系统就会自动处理序列化和反序列化。使用`writeObject()`和`readObject()`方法可以自定义序列化的行为。 优点: - 实现简单,只需要在类上添加`implements Serializable`即可。 - ...

    24、序列化 Serializable1

    3. **实现序列化** - 为了让一个类支持序列化,只需让该类实现`java.io.Serializable`接口。这个接口没有定义任何方法,只是一个标记接口,表明类的对象可以被序列化。 4. **序列化ID** - `serialVersionUID`是一...

    java序列化和反序列化的方法

    在本例中,我们使用 Serializable 接口实现序列化和反序列化,以便在网络上传输 UserMessage 对象。 Java 序列化和反序列化的优点包括: * 实现对象的持久化存储 * 实现对象的网络传输 * 实现对象的克隆 * 实现...

    可序列化接口Serializable

    在Java类定义中,只需添加`implements Serializable`即可实现序列化。例如: ```java public class MyClass implements Serializable { private int id; private String name; // ... } ``` **序列化标识符:...

    Java序列化(Serializable)与反序列化_.docx

    Java提供了内置的支持来实现序列化功能,这种支持主要体现在`Serializable`接口上。 #### 重要性及应用场景 序列化的重要性在于它能够帮助开发者解决以下问题: 1. **持久化存储**:将对象的状态存储到磁盘文件中...

    Java_Serializable(序列化)的理解和总结

    实现序列化(将对象保存到文件中)通常遵循以下步骤: 1. **创建`FileOutputStream`**:用于打开或创建一个文件,以便后续写入序列化后的数据。 ```java FileOutputStream fs = new FileOutputStream("foo.ser");...

    java序列化(Serializable)的作用和反序列化.pdf

    要实现序列化,对象的类必须实现`Serializable`接口。这通常意味着在类声明中添加`implements Serializable`。然后,可以使用`ObjectOutputStream`将对象写入文件,如下所示: - 创建`FileOutputStream`以指向要...

    Java序列化(Serializable)与反序列化__1.docx

    1. Object Serialize:Java内置的序列化机制,通过实现`Serializable`接口来实现对象的序列化。在进行反序列化时,Java会验证`serialVersionUID`,确保对象在序列化和反序列化之间的一致性。 2. JSON:通过将对象...

    序列化类的作用Serializable

    `Serializable`接口是Java中实现序列化的主要方式。 当一个类实现`Serializable`接口后,该类的对象就可以被序列化。这个接口没有定义任何方法,仅仅作为一个标记,表明该类及其所有子类都支持序列化。需要注意的是...

    用序列化(Serializable)保存、读取对象

    Java中的序列化是通过实现`java.io.Serializable`接口来标记一个类可以被序列化。这个接口是一个标记接口,没有定义任何方法,仅仅表示该类的对象可以被序列化。如果你希望一个类的实例能够被序列化,那么这个类就...

    IDEA中实体类实现了序列化接口

    ### IDEA中实体类实现序列化接口与序列化ID生成 #### 一、序言 在Java开发中,序列化是一项非常重要的技术,它允许将对象的状态转换为字节流,从而方便在网络上传输或者存储到磁盘上。为了保证序列化的兼容性与...

    C#自定义序列化ISerializable的实现方法

    下面我们将详细讲解如何在C#中实现自定义序列化,特别是通过ISerializable接口。 首先,让我们看看如何声明一个可序列化的类。在C#中,我们可以使用`[Serializable]`属性标记类,表明此类支持序列化。例如: ```...

    Java 串行化(序列化)Serializable/Externalizable

    4. **实现Serializable并提供serialVersionUID**:确保类的序列化兼容性,避免因类结构变化导致的反序列化失败。 **七、实战应用** 在实际项目中,例如在网络通信中传递复杂对象,或者是将对象持久化到数据库或文件...

    Java实现序列化例子

    在Java中,如果一个类需要支持序列化,那么这个类就需要实现`java.io.Serializable`接口,尽管该接口没有任何方法需要实现,但它的存在就标志着这个类的对象可以被序列化。 首先,我们来看一下`SerializableDemo`这...

Global site tag (gtag.js) - Google Analytics