2014-09-04 77 views
0

我有序列化和base64轉換對象的功能,反之亦然。它使用Newtonsoft序列化和反序列化對象。代碼的作品,但有沒有辦法做到這一點,而不使用牛頓軟件?序列化和Base64轉換,反之亦然vb.net

Public Shared Function SerializeAndBase64(ObjectToSerialize As Object) As ReturnObject(Of String) 
    Dim rtnObj As New ReturnObject(Of String) 
    Try 
     Dim SerializedObjectJson As String = Newtonsoft.Json.JsonConvert.SerializeObject(ObjectToSerialize) 
     Dim Base64String As String = Convert.ToBase64String(Encoding.UTF8.GetBytes(SerializedObjectJson)) 
     rtnObj.Item = Base64String 
    Catch ex As Exception 
     rtnObj.ErrorID = ErrorHandler.handleError(ex) 
     rtnObj.ErrorMessage = ex.Message 
     rtnObj.IsError = True 
    End Try 
    Return rtnObj 
End Function 

Public Shared Function DeserializeFromBase64(Of t)(Base64Json As String) As ReturnObject(Of t) 
    Dim rtnObj As New ReturnObject(Of t) 
    Try 


     Dim SerializedObjectJson As String = Encoding.UTF8.GetString(Convert.FromBase64String(Base64Json)) 
     Dim DeserializedObject As t = Newtonsoft.Json.JsonConvert.DeserializeObject(Of t)(SerializedObjectJson) 
     rtnObj.Item = DeserializedObject 
    Catch ex As Exception 
     rtnObj.ErrorID = ErrorHandler.handleError(ex) 
     rtnObj.ErrorMessage = ex.Message 
     rtnObj.IsError = True 
    End Try 
    Return rtnObj 
End Function 

在此先感謝。

+0

是的,還有其他序列化器,如果這是你問。 NET包含BinaryFomratter;還有Protobuf-net和MetSerializer – Plutonix 2014-09-04 11:35:38

+0

@Plutonix:[protobuf] +1(https://code.google.com/p/protobuf-net/wiki/Performance),同時檢查[proto#](https:/ /code.google.com/p/protosharp/)。 – Neolisk 2014-09-04 14:51:31

+0

如果您需要字符串序列化,請選中[DataContractJsonSerializer類](http://msdn.microsoft.com/zh-cn/library/system.runtime.serialization.json.datacontractjsonserializer(v = vs.110).aspx)。 – Neolisk 2014-09-04 14:53:12

回答

0

你可以自己序列化/反序列化它。你只需要想出一種方法將所有內容保存到單個字符串中,或​​者如果需要,也可以將其保存爲XML或甚至是字節數組。你的選擇。

Public Class Class1 
    Public Property MyValue As String 

    Public Function Serialize() As String 
     Return MyValue 
    End Function 

    Public Sub Deserialize(ByVal value As String) 
     MyValue = value 
    End Sub 
End Class 
相關問題