Json的序列化和反序列化
1.定义数据类
[ Serializable ]
public class ZoomPoint
{
public string name;
public Vector2 pivot = Vector2. one / 2 ;
public float zoomMagnification = 5f ;
public float time = 1.0f ;
public override string ToString ( )
{
return $"name = { this . name} , pivot = ( { pivot. ToString ( ) } ), zoomMagnification = { this . zoomMagnification} , time = { this . time} " ;
}
}
2. 定义Json存储类
[ Serializable]
public class Data {
public List< ZoomPoint> zoomPoints;
}
3.序列化
public void WriteDataTest ( ) {
Data data = new ( )
{
zoomPoints = new List< ZoomPoint> ( )
} ;
ZoomPoint point1 = new ZoomPoint
{
name = "1" ,
pivot = new Vector2 ( 0.75f , 0.75f )
} ;
ZoomPoint point2 = new ZoomPoint
{
name = "2" ,
pivot = new Vector2 ( 0.5f , 0.5f )
} ;
data. zoomPoints[ 0 ] = point1;
data. zoomPoints[ 1 ] = point2;
string js = JsonUtility. ToJson ( data) ;
string fileUrl;
if ( filePath == "" ) {
fileUrl = Application. streamingAssetsPath + jsonFileName;
} else {
fileUrl = filePath;
}
using ( StreamWriter sw = new StreamWriter ( fileUrl) )
{
sw. WriteLine ( js) ;
sw. Close ( ) ;
sw. Dispose ( ) ;
}
}
4.反序列化
public Data ReadData ( ) {
string fileUrl;
if ( filePath == "" ) {
fileUrl = Application. streamingAssetsPath + jsonFileName;
} else {
fileUrl = filePath;
}
string readDate;
using ( StreamReader sr = File. OpenText ( fileUrl) ) {
readDate = sr. ReadLine ( ) ;
sr. Close ( ) ;
}
Data data = JsonUtility. FromJson < Data> ( readDate) ;
if ( data == null ) {
data = new Data ( ) {
zoomPoints = new List< ZoomPoint> ( )
} ;
return data;
}
foreach ( ZoomPoint zp in data. zoomPoints) {
dict. TryAdd ( zp. name, zp) ;
}
return data;
}
数据存储效果:
Xml的序列化和反序列化
1.定义数据类
public class XmlText {
public string name;
public string value ;
public List< int > list;
public override string ToString ( ) {
return $"name = { name } , value = { value } , list = { list } " ;
}
}
2.序列化
public void Init ( ) {
test = new XmlText ( ) {
name = "Xml测试" ,
value = "value" ,
list = new List< int > ( )
} ;
test. list. Add ( 1 ) ;
test. list. Add ( 3 ) ;
test. list. Add ( 100 ) ;
}
public void XmlSerialize ( ) {
FileStream fileStream = new FileStream ( Application. streamingAssetsPath + "/text.xml" , FileMode. OpenOrCreate, FileAccess. ReadWrite, FileShare. ReadWrite) ;
StreamWriter sw = new StreamWriter ( fileStream, System. Text. Encoding. UTF8) ;
XmlSerializer xml = new XmlSerializer ( test. GetType ( ) ) ;
xml. Serialize ( sw, test) ;
sw. Close ( ) ;
fileStream. Close ( ) ;
}
3.反序列化
public XmlText Deserialize ( ) {
FileStream fs = new FileStream ( Application. streamingAssetsPath + "/text.xml" , FileMode. OpenOrCreate, FileAccess. ReadWrite, FileShare. ReadWrite) ;
XmlSerializer xml = new XmlSerializer ( typeof ( XmlText ) ) ;
XmlText result = ( XmlText) xml. Deserialize ( fs) ;
fs. Close ( ) ;
return result;
}
结果: