C# JSON字符串反序列化

7

我真的很难找到任何关于C#中JSON反序列化的例子,其中每个JSON项的第一个属性是不同的ID。

    {
       "12112083":{
           "Topic_ID":"12112083",
           "Moved_ID":"51",
           "subject":"subject text goes here"      
           },
       "12111966":{
           "Topic_ID":"12111966",
           "Moved_ID":"51",
           "subject":"another subject text"      
           },
       "12106917":{
           "Topic_ID":"12106917",
           "Moved_ID":"0",
           "subject":"test"      
           }
    }

我尝试了几种不同的方法,但都没有成功。我无法控制返回的JSON有时是单个项目,有时是项数组,就像上面的例子一样。如果可能的话,最好将其反序列化为类型化的对象类。谢谢。
    '{"12112083":{"Topic_ID":"12112083","Moved_ID":"51","subject":"Due to a computer virus, many of my files are \u005C"Crypted\u005C",espe","Start_date":"10/6/2012 6:54:37 PM","InitialResponseDueDate":"10/6/2012 7:01:37 PM","Locked":"0","QValue":"$10","Status":"1","Author_ID":"71318191","Question_Text":"Due to a computer virus, many of my files are \u005C"Crypted\u005C",especially my pictures.  Now my FinepixA500 camera will not upload photos to my computer (laptop).  Geek Squad could not crack the code and suggested that I contact Toshiba and have them reset the computer to its original manufacturer settings.  If I do that, I will lose all of my data.  The only thing that appears not to be working is \u005C"photo gallery\u005C". (therefore, my camera will not upload photos anymore.....) Any suggestions?","Username":"JACUSTOMER-iei7o0tr-","No_of_Questions":"0","No_of_Accepts":"0","Last_visit":"10/6/2012 7:22:18 PM","Join_Date":"10/6/2012 6:46:29 PM","lastExpert":"","IsPress":"False","hasCustomerOptOuts":"0","RecCount":"0","OptedOut":"","Urgency":"51","AuthorHasSubscription":"False","Relisted":"0","IsAbandoned":"False","categoryName":"Camera and Video","categoryName_Additional":"Laptop","QuestionCommissionHasAdjusted":"False","LockedBy":"-1","IsOnline":"False","QuestionLink":"/video-camera-repair/77lqr-due-computer-virus-files-crypted-espe.html","WaitingForYou":"False","RequestedForYou":"False","IsChatEnabled":"False","ChangedKeyList":"","DeltaType":"A"},"12111966":{"Topic_ID":"12111966","Moved_ID":"51","subject":"office/outlook for mac 2011 keeps hanging upMicrosoft Error","Start_date":"10/6/2012 6:25:06 PM","InitialResponseDueDate":"10/6/2012 7:25:06 PM","Locked":"0","QValue":"$19","Status":"1","Author_ID":"71317792","Question_Text":"office/outlook for mac 2011 keeps hanging upMicrosoft Error Reporting log version: 2.0<br/><br/>Error Signature:<br/>Exception: EXC_CRASH (SIGTRAP)<br/>Date/Time: 2012-10-06 17:59:38 +0000<br/>Application Name: Microsoft Outlook<br/>Application Bundle ID: com.microsoft.Outlook<br/>Application Signature: OPIM<br/>Application Version: 14.2.4.120824<br/>Crashed Module Name: merp<br/>Crashed Module Version: 2.2.4.120824<br/>Crashed Module Offset: 0x00003aa2<br/>Blame Module Name: Microsoft Outlook<br/>Blame Module Version: 14.2.4.120824<br/>Blame Module Offset: 0x003c900c<br/>Application LCID: 1033<br/>Extra app info: Reg=en Loc=0x0409<br/>Crashed thread: 10","Username":"JACUSTOMER-wr0d1qwb-","No_of_Questions":"0","No_of_Accepts":"0","Last_visit":"10/6/2012 6:54:53 PM","Join_Date":"10/6/2012 6:25:00 PM","lastExpert":"","IsPress":"False","hasCustomerOptOuts":"0","RecCount":"0","OptedOut":"","Urgency":"51","AuthorHasSubscription":"False","Relisted":"0","IsAbandoned":"False","categoryName":"Microsoft Office","categoryName_Additional":"","QuestionCommissionHasAdjusted":"False","LockedBy":"-1","IsOnline":"False","QuestionLink":"/microsoft-office/77lni-office-outlook-mac-2011-keeps-hanging-upmicrosoft-error.html","WaitingForYou":"False","RequestedForYou":"False","IsChatEnabled":"True","ChangedKeyList":"","DeltaType":"A"},"12106917":{"Topic_ID":"12106917","Moved_ID":"0","subject":"test","Start_date":"10/5/2012 6:22:42 PM","InitialResponseDueDate":"10/5/2012 6:40:42 PM","Locked":"0","QValue":"$21","Status":"1","Author_ID":"69617617","Question_Text":"test","Username":"JACUSTOMER-dwbsyao6-","No_of_Questions":"4","No_of_Accepts":"1","Last_visit":"10/6/2012 11:12:19 AM","Join_Date":"7/16/2012 12:59:47 PM","lastExpert":"","IsPress":"False","hasCustomerOptOuts":"0","RecCount":"0","OptedOut":"","Urgency":"0","AuthorHasSubscription":"True","Relisted":"0","IsAbandoned":"False","categoryName":"Computer","categoryName_Additional":"","QuestionCommissionHasAdjusted":"True","LockedBy":"-1","IsOnline":"True","QuestionLink":"/computer/77hr9-test.html","WaitingForYou":"False","RequestedForYou":"False","IsChatEnabled":"True","ChangedKeyList":"","DeltaType":"A"}}'

我收到了"InvalidCastException"错误,无法将类型为'System.String'的对象转换为类型'Newtonsoft.Json.Linq.JObject'。
我尝试从字符串的开头和结尾中删除单引号,但是仍然得到相同的错误信息?

PST - 我已经在上面的问题中添加了实际的JSON字符串。原始的JSON字符串是格式化和剥离版本,以概括我的问题。 - user1462387
我移除了我的-1。但是,请确保在问题中包含实际使用的代码-这有助于细化/聚焦问题。 - user166390
好的,谢谢,我接受你的意见。这是我的第一篇帖子,说实话可能有点匆忙。 - user1462387
3个回答

10

使用Json.Net

(所发布的JSON无效。在将无效的\u005C"替换为\u005C之后,以下内容有效。)

string json = @"{""12112083"":{""Topic_ID"":""12112083"",""Moved_ID"":""51"",""subject"":""Due to a computer virus, many of my files are \u005CCrypted\u005C,espe"",""Start_date"":""10/6/2012 6:54:37 PM"",""InitialResponseDueDate"":""10/6/2012 7:01:37 PM"",""Locked"":""0"",""QValue"":""$10"",""Status"":""1"",""Author_ID"":""71318191"",""Question_Text"":""Due to a computer virus, many of my files are \u005CCrypted\u005C,especially my pictures.  Now my FinepixA500 camera will not upload photos to my computer (laptop).  Geek Squad could not crack the code and suggested that I contact Toshiba and have them reset the computer to its original manufacturer settings.  If I do that, I will lose all of my data.  The only thing that appears not to be working is \u005Cphoto gallery\u005C. (therefore, my camera will not upload photos anymore.....) Any suggestions?"",""Username"":""JACUSTOMER-iei7o0tr-"",""No_of_Questions"":""0"",""No_of_Accepts"":""0"",""Last_visit"":""10/6/2012 7:22:18 PM"",""Join_Date"":""10/6/2012 6:46:29 PM"",""lastExpert"":"""",""IsPress"":""False"",""hasCustomerOptOuts"":""0"",""RecCount"":""0"",""OptedOut"":"""",""Urgency"":""51"",""AuthorHasSubscription"":""False"",""Relisted"":""0"",""IsAbandoned"":""False"",""categoryName"":""Camera and Video"",""categoryName_Additional"":""Laptop"",""QuestionCommissionHasAdjusted"":""False"",""LockedBy"":""-1"",""IsOnline"":""False"",""QuestionLink"":""/video-camera-repair/77lqr-due-computer-virus-files-crypted-espe.html"",""WaitingForYou"":""False"",""RequestedForYou"":""False"",""IsChatEnabled"":""False"",""ChangedKeyList"":"""",""DeltaType"":""A""},""12111966"":{""Topic_ID"":""12111966"",""Moved_ID"":""51"",""subject"":""office/outlook for mac 2011 keeps hanging upMicrosoft Error"",""Start_date"":""10/6/2012 6:25:06 PM"",""InitialResponseDueDate"":""10/6/2012 7:25:06 PM"",""Locked"":""0"",""QValue"":""$19"",""Status"":""1"",""Author_ID"":""71317792"",""Question_Text"":""office/outlook for mac 2011 keeps hanging upMicrosoft Error Reporting log version: 2.0<br/><br/>Error Signature:<br/>Exception: EXC_CRASH (SIGTRAP)<br/>Date/Time: 2012-10-06 17:59:38 +0000<br/>Application Name: Microsoft Outlook<br/>Application Bundle ID: com.microsoft.Outlook<br/>Application Signature: OPIM<br/>Application Version: 14.2.4.120824<br/>Crashed Module Name: merp<br/>Crashed Module Version: 2.2.4.120824<br/>Crashed Module Offset: 0x00003aa2<br/>Blame Module Name: Microsoft Outlook<br/>Blame Module Version: 14.2.4.120824<br/>Blame Module Offset: 0x003c900c<br/>Application LCID: 1033<br/>Extra app info: Reg=en Loc=0x0409<br/>Crashed thread: 10"",""Username"":""JACUSTOMER-wr0d1qwb-"",""No_of_Questions"":""0"",""No_of_Accepts"":""0"",""Last_visit"":""10/6/2012 6:54:53 PM"",""Join_Date"":""10/6/2012 6:25:00 PM"",""lastExpert"":"""",""IsPress"":""False"",""hasCustomerOptOuts"":""0"",""RecCount"":""0"",""OptedOut"":"""",""Urgency"":""51"",""AuthorHasSubscription"":""False"",""Relisted"":""0"",""IsAbandoned"":""False"",""categoryName"":""Microsoft Office"",""categoryName_Additional"":"""",""QuestionCommissionHasAdjusted"":""False"",""LockedBy"":""-1"",""IsOnline"":""False"",""QuestionLink"":""/microsoft-office/77lni-office-outlook-mac-2011-keeps-hanging-upmicrosoft-error.html"",""WaitingForYou"":""False"",""RequestedForYou"":""False"",""IsChatEnabled"":""True"",""ChangedKeyList"":"""",""DeltaType"":""A""},""12106917"":{""Topic_ID"":""12106917"",""Moved_ID"":""0"",""subject"":""test"",""Start_date"":""10/5/2012 6:22:42 PM"",""InitialResponseDueDate"":""10/5/2012 6:40:42 PM"",""Locked"":""0"",""QValue"":""$21"",""Status"":""1"",""Author_ID"":""69617617"",""Question_Text"":""test"",""Username"":""JACUSTOMER-dwbsyao6-"",""No_of_Questions"":""4"",""No_of_Accepts"":""1"",""Last_visit"":""10/6/2012 11:12:19 AM"",""Join_Date"":""7/16/2012 12:59:47 PM"",""lastExpert"":"""",""IsPress"":""False"",""hasCustomerOptOuts"":""0"",""RecCount"":""0"",""OptedOut"":"""",""Urgency"":""0"",""AuthorHasSubscription"":""True"",""Relisted"":""0"",""IsAbandoned"":""False"",""categoryName"":""Computer"",""categoryName_Additional"":"""",""QuestionCommissionHasAdjusted"":""True"",""LockedBy"":""-1"",""IsOnline"":""True"",""QuestionLink"":""/computer/77hr9-test.html"",""WaitingForYou"":""False"",""RequestedForYou"":""False"",""IsChatEnabled"":""True"",""ChangedKeyList"":"""",""DeltaType"":""A""}}";

var jobj = (JObject)JsonConvert.DeserializeObject(json);
var items = jobj.Children()
    .Cast<JProperty>()
    .Select(j=>new
    {
        ID=j.Name,
        Topic = (string)j.Value["Topic_ID"],
        Moved = (string)j.Value["Moved_ID"],
        Subject = (string)j.Value["subject"],
    })
    .ToList();

谢谢L.B,我已经编辑了问题并提供了更多细节,以及在尝试您上面的代码示例后收到的异常。 - user1462387
@user1462387 如果您修复了 JSON(它是无效的),则会发现上面的代码可以正常工作,没有任何异常。 - L.B
谢谢,我刚刚注意到 JSON 中反斜杠的 Unicode 字符 "\u005C" 可能会导致问题。由于我无法控制提供给我的 JSON,因此需要进行替换。 - user1462387
@user1462387,问题不在于\u005C字符,而在于你的JSON中的\u005C" - L.B
@L.B:无法访问子值,显示异常。你的解决方案不起作用。 - Jasmine
@L.B:谢谢你,但我的情况略有不同,很遗憾你的方法并没有帮到我,我还需要纠正我的错误。 - Jasmine

2

我使用System.Web写了一个小方法,在每个使用JSON数据存储的项目中都可以使用:

private T UnpackJson<T>(object data)
{
    var serializer = new JavaScriptSerializer();
    string rawJSON = serializer.Serialize(data);

    var result = serializer.Deserialize<T>(rawJSON);
    return result;
}

...其中 T 是一种类型,其元素与您正在反序列化的模式匹配。对于您在顶部给出的 blob,我建议使用以下内容:

// Using my above method...
var x = UnpackJson<Foo[]>(blob);

public class Foo
{
    public string ID;
    public Bar SubItem;
}

public class Bar
{
    public int Topic_ID;
    public int Subject_ID;
    public string subject; 
}

注意,你的变量名应该完全与JSON数据中的属性名相匹配!我希望这样可以成功(请注意,虽然我使用了这种方法并且确信它可以将JSON数据反序列化为类,但这个实现未经过测试。)


0
使用 JSON.NET - .NET 的免费 JSON 解析器/序列化器。

2
请在给出具体结构的情况下包含相关用法示例。 - user166390
谢谢,我实际上正在使用JSON.NET,但我正在努力反序列化JSON的结构。 - user1462387

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接