在C#和Android应用之间序列化数据的最简单方法



我有一个用C#编写的桌面应用程序,该应用程序将与Android应用程序通信。通过TCP/IP连接传递数据之间的最简单方法是什么?我对性能不太感兴趣,对易于实施更感兴趣。

我自然不理解您, ease of implementation 。但是正如我猜想的那样,您应该需要这些:

In [C#]:

//util function
public static void WriteBuffer(BinaryWriter os, byte[] array) {
            if ((array!=null) && (array.Length > 0) && (array.Length < MAX_BUFFER_SIZE)) {
                WriteInt(os,array.Length);
                os.Write(array);
            } else {
                WriteEmptyBuffer(os);
            }
        }
//write a string
public static void WriteString(BinaryWriter os, string value)  {
            if (value!=null) {
                byte[] array = System.Text.Encoding.Unicode.GetBytes(value);
                WriteBuffer(os,array);
            } else {
                WriteEmptyBuffer(os);
            }
        }

In [Java] Android:

/** Read a String from the wire.  Strings are represented by
 a length first, then a sequence of Unicode bytes. */
public static String ReadString(DataInputStream input_stream) throws IOException  
{
    String ret = null;
    int len = ReadInt(input_stream);
    if ((len == 0) || (len > MAX_BUFFER_SIZE)) {
        ret = "";
    } else {
        byte[] buffer = new byte[len];
        input_stream.readFully(buffer);
        ret = new String(buffer, DATA_CHARSET);
    }
    return (ret);
}   

有关进一步的结构数据,例如您要在C#和Java之间发送对象,请使用 XML Serialization in C# XML Parser in Java 。您可以在互联网上搜索这些;许多示例在代码项目网站上。

在Android零件中,您可以使用 XSTREAM 库易于使用。

最新更新