【发布时间】:2013-12-13 22:56:59
【问题描述】:
我想加载一个保存为 base64 的字符串,但我总是收到此错误。我正在使用 SimpleJson 类(http://wiki.unity3d.com/index.php/SimpleJSON):
异常:反序列化 JSON 时出错。未知标签:66 SimpleJSON.JSONNode.Deserialize (System.IO.BinaryReader aReader)(位于 Assets/plugins/SimpleJSON.cs:512)
我的代码:
var I = new JSONClass();
I["author"]["name"] = "testName";
I["author2"]["name2"] = "testName2";
string str = I.SaveToCompressedBase64();
//output : QlpoOTFBWSZTWdFZTaIAAAdNgH/gEAAA etc.
//#Error deserializing JSON
string res = JSONClass.LoadFromBase64( str );//.ToString();
以下是类中的方法:
public static JSONNode LoadFromBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromStream(stream);
}
public static JSONNode LoadFromStream(System.IO.Stream aData)
{
using(var R = new System.IO.BinaryReader(aData))
{
return Deserialize(R);
}
}
public static JSONNode Deserialize(System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
switch(type)
{
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for(int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32();
JSONClass tmp = new JSONClass();
for(int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData(aReader.ReadString());
}
case JSONBinaryTag.IntValue:
{
return new JSONData(aReader.ReadInt32());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData(aReader.ReadDouble());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData(aReader.ReadBoolean());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
谢谢
【问题讨论】:
-
您正在尝试解析压缩字符串。在尝试解析之前尝试解压缩 base64 字符串。
-
@rdodev 谢谢,你能告诉我怎么做吗?我尝试
var base64 = System.Convert.FromBase64String(str);,但似乎不是这样做的方法。 -
我下面的回答应该会有所帮助。
标签: c# string encoding utf-8 base64