0

步骤 1. 将第一条消息反序列化到 dictionary1 (receivedDict)

步骤 2. 将 dictionary1["data"] 反序列化为 dictionary2 (receivedDict2)

每当第二层包含另一个序列化数组时,它就会失败。如果没有,它会起作用。第三步是反序列化 dictionary2["replaceArray"] 但由于错误,我没有达到那个阶段。

挑剔:

在此处输入图像描述

编码:

CGlobals.output("Received a message with length: " + _message.Length);
Console.WriteLine("message Contains : " + _message);

//Unserialize main message
Dictionary<string, string> receivedDict = new Dictionary<string, string>();
try
{
    receivedDict = CJsonStuff.unserializeDict(_message);
}
catch (Exception ex) { return retError(1, ex.Message,false); }
if (receivedDict.Count < 1) return retError(2, "",false);

//List all elements for debugging.
string temp = "";
foreach (KeyValuePair<string, string> item in receivedDict)
{
    temp += item.Key + " : " + item.Value + "\n";
}
Console.WriteLine("\n" + temp + "\n");

//Parse jobID
int jobID = -1;
try
{
    jobID = Int32.Parse(receivedDict["jobID"]);
}
catch (Exception ex) { return retError(3, ex.Message,false); }

//Parse alteredID
int alteredID = -1;
bool isAltered = false;
try
{
    Dictionary<string, string> receivedDict2 = new Dictionary<string, string>();
    Console.WriteLine("Unserializing : "+receivedDict["data"]);
    receivedDict2 = CJsonStuff.unserializeDict(receivedDict["data"]); //Error occurs here
    Console.WriteLine("Unserialized data");

    //Show all elements for debugging.
    string temp2 = "";
    foreach (KeyValuePair<string, string> item in receivedDict2)
    {
        temp2 += item.Key + " : " + item.Value + "\n";
    }
    Console.WriteLine("\n" + temp2 + "\n");

    if (receivedDict2.ContainsKey("alteredID"))
    {
        alteredID = Int32.Parse(receivedDict2["alteredID"]);
        isAltered = true;
    }
}
catch (Exception ex) { Console.WriteLine(ex.Message); return retError(6, ex.Message, false, jobID); }

CJSonStuff:

public static Dictionary<string, string> unserializeDict(string thestring)
{
    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(thestring);
    return dict;
}

所以基本上,它可以很好地反序列化第一条消息,即使它包含一个嵌入式序列化数组,但是尝试再次执行完全相同的操作失败了。我该如何解决这个问题?

4

1 回答 1

1

那是因为它data 一个字符串,它不是一个 JSON 对象,它是一个 JSON 对象的字符串表示,这是一个很大的区别(注意"开头和结尾的data)。

据我所知,您不能将 JSON 对象反序列化为字符串,这样做对我来说没有意义。您应该将其反序列化为JObjector Dictionary<string, object>,或者(如果数据没有更改,则为最佳选择)为此创建一个类并反序列化为该类。

于 2012-04-22T15:09:30.653 回答