C# DataContractJsonSerializer 抛出异常 期望状态 'Element'.. 遇到名称为 ''、命名空间为 '' 的 'Text'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9605397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:06:48  来源:igfitidea点击:

DataContractJsonSerializer throws exception Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''

c#jsonserialization

提问by FatAlbert

I need help to serialize a piece of json.

我需要帮助来序列化一段 json。

I get a response from a rest service, the service is returning json. After that I want to map the request to a class. I'm using the DataContractJsonSerializer, but I can't get it to work.

我收到了来自休息服务的响应,该服务正在返回 json。之后我想将请求映射到一个类。我正在使用 DataContractJsonSerializer,但我无法让它工作。

When the data is serialize the following exception is thrown:

当数据被序列化时,抛出以下异常:

"Expecting state 'Element'.. Encountered 'Text'  with name '', namespace ''. "

Here is the code:

这是代码:

HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

Stream responseStreamm = response.GetResponseStream();

StreamReader reader = new StreamReader(responseStreamm);

string streamAsString = reader.ReadToEnd();

MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(streamAsString)) {Position = 0};

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<MyClass>));

List<MyClass> myClass = (List<MyClass>)serializer.ReadObject(memoryStream);

And here is the MyClass:

这是 MyClass:

[DataContract]
public class MyClass
{
    [DataMember]
    public string RawData { get; set; }

    [DataMember]
    public string StudentIdentity { get; set; }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }

    [DataMember]
    public string SchoolName { get; set; }

    [DataMember]
    public string SchoolCode { get; set; }

    [DataMember]
    public string TypeOfEducation { get; set; }

    [DataMember]
    public string EducationCode { get; set; }

    [DataMember]
    public string NationalProgram { get; set; }

    [DataMember]
    public string Objective { get; set; }

    [DataMember]
    public string IssuingDate { get; set; }

    [DataMember]
    public string GradeType { get; set; }

    [DataMember]
    public string ProgramRange { get; set; }

    [DataMember]
    public string HourTotal { get; set; }

    [DataMember]
    public string BasicEligibility { get; set; }

    [DataMember]
    public string OccupationCompetence { get; set; }

    [DataMember]
    public string CourseOfStudyFromSchool { get; set; }

    [DataMember]
    public string Software { get; set; }

    [DataMember]
    public string SoftwareProvider { get; set; }

    [DataMember]
    public string ProgramType { get; set; }

    [DataMember]
    public string Note { get; set; }
}

The response from the service is:

来自服务的响应是:

"[{\"RawData\":\"\",\"StudentIdentity\":\"450101\",\"FirstName\":\"Kalle\",\"LastName\":\"Karlsson\",\"SchoolName\":\"\",\"SchoolCode\":\"SKL123\",\"TypeOfEducation\":\"\",\"EducationCode\":\"Code\",\"NationalProgram\":\"\",\"Objective\":\"Obj\",\"IssuingDate\":\"2012-01-28\",\"GradeType\":\"GradeType\",\"ProgramRange\":\"1\",\"HourTotal\":\"2000\",\"BasicEligibility\":\"BE\",\"OccupationCompetence\":\"OC\",\"CourseOfStudyFromSchool\":\"Y\",\"Software\":\"HAL213\",\"SoftwareProvider\":\"SchoolSoft\",\"ProgramType\":\"C\",\"Note\":\"Notering\",\"CourseInformation\":[{\"CourseCode\":\"ABC555\",\"Grade\":\"VG\",\"GradeDate\":\"2012-01-28\",\"Points\":\"50\",\"Comment1\":\"Kommentar1\",\"Comment2\":\"\",\"Comment3\":\"\",\"AddtionalInformation\":\"Info\",\"Exceptions\":null},{\"CourseCode\":\"DFG333\",\"Grade\":\"G\",\"GradeDate\":\"2012-01-28\",\"Points\":\"60\",\"Comment1\":\"\",\"Comment2\":\"\",\"Comment3\":\"\",\"AddtionalInformation\":\"\",\"Exceptions\":null}],\"Exceptions\":[]}]"

Help is much appreciated!

非常感谢帮助!

Edit:

编辑:

I'm complementing with the service code:

我正在补充服务代码:

List<MyClass> myClass = validationManager.GetXmlAsAListOfEducationInformationObject();

JavaScriptSerializerserializer = new JavaScriptSerializer();

string jsonData = serializer.Serialize(myClass);

return jsonData;

采纳答案by George Siggouroglou

I had the same issue.

我遇到过同样的问题。

I was sending a JSON object from client(browser-using jQuery) to my server application (IIS-ASP.NET using c#).

我正在从客户端(使用浏览器使用 jQuery)向我的服务器应用程序(使用 c# 的 IIS-ASP.NET)发送一个 JSON 对象。

The JSON includes inner JSON objects and there the problem exists.

JSON 包含内部 JSON 对象,因此存在问题。

Below I list the JSON object (in a minimal version for the example case), the c# classes that must be constructed and the code that deserializes the JSON to the C# data classes.

下面我列出了 JSON 对象(示例案例的最小版本)、必须构造的 c# 类以及将 JSON 反序列化为 C# 数据类的代码。

JSON object:

JSON 对象:

"{"Conference_id":"9","SubmissionType":{"Value":"1"},"TextPublishType":[{"Value":"12"},{"Value":"9"}],"Title":"aTitle"}"  

Be carefull: The SubmissionType property includes an inner JSON as its value and the TextPublishType property includes an array of JSON object as its value.

注意:SubmissionType 属性包含一个内部 JSON 作为其值,TextPublishType 属性包含一个 JSON 对象数组作为其值。

C# class that mustbe constructed(depends on the JSON structure):

必须构造的C# 类(取决于 JSON 结构):

public class Abstract 
{
    public int Conference_id { get; set; }
    public SubmissionTypeClass SubmissionType { get; set; }
    public List<TextPublishTypeClass> TextPublishType{ get; set; }
}  

The SubmissionType defined as a different class cause it includes an inner JSON object.
The TextPublishType defined as a list of a different class cause it includes an inner array JSON object.

SubmissionType 定义为不同的类,因为它包含一个内部 JSON 对象。
TextPublishType 定义为不同类的列表,因为它包含一个内部数组 JSON 对象。

public class SubmissionTypeClass 
{
    public int Value { get; set; }
}

public class TextPublishTypeClass 
{
    public int Value { get; set; }
}

This two classes include only one property. This is because on the JSON object the inner JSON include only one property(Value). This is a simple example just for the answer case. If you want more properties on the JSON object then you have to define them with the same key nameon the class definition.

这两个类只包含一个属性。这是因为在 JSON 对象上,内部 JSON 仅包含一个属性(值)。这是一个简单的例子,仅适用于答案案例。如果您想要 JSON 对象上的更多属性,那么您必须在类定义中使用相同的键名定义它们。

The deserialization code:

反序列化代码:

Abstract theAbstract = Activator.CreateInstance<Abstract>();
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes("the above JSON text"));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(theAbstract.GetType());
theAbstract = (Abstract)serializer.ReadObject(memoryStream);
memoryStream.Dispose();

For more complex JSON objects the only thing to do is to create a more complex class structure.
I hope that it will help.

对于更复杂的 JSON 对象,唯一要做的就是创建更复杂的类结构。
我希望它会有所帮助。

回答by Dan Fitch

That service response works when I deserialize it, which leads me to suspect your extra dancing with the MemoryStream is causing a null stream somewhere. Just simplify it and pass the response stream straight to the serializer:

当我反序列化它时,该服务响应有效,这使我怀疑您与 MemoryStream 的额外跳舞会导致某处出现空流。只需简化它并将响应流直接传递给序列化程序:

HttpWebResponse response = webRequest.GetResponse();
var serializer = new DataContractJsonSerializer(typeof(List<MyClass>));
var list = (List<MyClass>)serializer.ReadObject(response.GetResponseStream());