将3层数组反序列化为Dictionaries

时间:2012-04-22 14:55:00

标签: c# json json.net

步骤1.将第一封邮件反序列化为dictionary1(receivedDict)

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

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

Piccy:

enter image description here

代码:

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;
}

所以基本上,即使它包含一个嵌入的序列化数组,它也会很好地反序列化第一个消息,但是尝试再次完成相同的操作失败了......我该如何修复它?

1 个答案:

答案 0 :(得分:1)

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

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