简体   繁体   English

当我尝试反序列化时,DataContractSerializer 为所有变量返回 null

[英]DataContractSerializer returns null for all the variables when I try to deserialize

I have a problem where DataContractSerializer returns null for all my variable.我有一个问题,DataContractSerializer 为我的所有变量返回 null。 It's like it doesn't see them or something.就好像它没有看到它们什么的。 I'm using it to deserialize a json file into an object.我正在使用它将 json 文件反序列化为一个对象。 I had it working for another json file that was using another class with 3 string attributes.我让它为另一个 json 文件工作,该文件使用另一个具有 3 个字符串属性的类。 This one is composed of 40 attributes mostly string and a few bool.这个由 40 个属性组成,主要是字符串和一些布尔值。 I have been working on it for hours and I just can't seem to find what I'm doing wrong.我已经研究了几个小时,我似乎无法找到我做错了什么。 I even tried it with only 1 string attribute and it still returned null.我什至只用 1 个字符串属性尝试过它,它仍然返回 null。 Here is a simplified version with only 1 string attribute and 1 bool attribute.这是一个只有 1 个 string 属性和 1 个 bool 属性的简化版本。 Any advice is more than appreciated.任何建议都非常感谢。

Thank you谢谢

Json : [{"Proposal_x0020_Type":"Lite Proposal","BI_x0020_Criteria_x0020_1":true}] Json: [{"Proposal_x0020_Type":"Lite Proposal","BI_x0020_Criteria_x0020_1":true}]

Function that tries to deserialize the string:尝试反序列化字符串的函数:

public Proposal[] Deserializer(string jsonFile)
    {

        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonFile));

        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Proposal[]));

        Proposal[] projectArr = (Proposal[])deserializer.ReadObject(ms);

        Console.WriteLine(jsonFile);

        Console.ReadLine();

        return projectArr;

    }

Class of the object that the deserializer should create: namespace PMIS反序列化器应该创建的对象的类:命名空间 PMIS

{ {

 [DataContract]

public class Proposal

{

    [DataMember(Order = 0)]

    public string Proposal_x0020_Type { get; set; }

    [DataMember(Order = 1)]

    public bool BI_x0020_Criteria_x0020_1 { get; set; }

}

} }

I managed to find the problem by comparing the code of this Deserialization to a previous one that I had.我通过将这个反序列化的代码与我之前的代码进行比较,设法找到了问题所在。 The only difference was the name of the variables inside the Json file.唯一的区别是 Json 文件中变量的名称。 The fact that they contain the Unicode for space (x00200) causes some problem inside the DataContractDeserializer.它们包含空间的 Unicode (x00200) 的事实导致 DataContractDeserializer 内部出现一些问题。 I believe that it is seeing it as space, so instead of seeing "Proposal_x0020_Type", it is seeing "Proposal_ _Type", but I'm not sure about it.我相信它把它看作是空间,所以它看到的不是“Proposal_x0020_Type”,而是“Proposal_ _Type”,但我不确定。 Anyway, the solution was to remove x0020 from all the variables inside the Json file.无论如何,解决方案是从 Json 文件中的所有变量中删除 x0020。 After that it worked perfectly fine.之后它工作得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM