反序列化JSON对象.Net

时间:2014-02-23 22:02:32

标签: .net json javascriptserializer

我正在尝试反序列化以下JSON对象:

"{\"results\":[{\"isError\":true,\"result\":null,\"messages\":[{\"type\":0,\"text\":\"Legal Entity is required when a Cost Center Code is specified: External Code 1 = cc3f25a7-0e8a-4e1c-8e18-c83c520ff3d7;\"}]}],\"isError\":true,\"sessionId\":null,\"tk\":null,\"tp\":null}"

我有以下课程: [DataContract]

public class BigCenterResponse
{
    [DataMember(Name = "isError")]
    public bool IsError { get; set; }

    [DataMember(Name = "sessionId")]
    public string SessionID { get; set; }

    [DataMember(Name = "results")]
    public List<Result> Responses { get; set; } 

}

[DataContract]
public class Message
{
    [DataMember(Name = "type")]
    public int Type { get; set; }

    [DataMember(Name = "text")]
    public string Text { get; set; }
}

[DataContract]
public class Result
{
    [DataMember(Name = "isError")]
    public bool IsError { get; set; }

    [DataMember(Name="messages")]
    public List<Message> Messages { get; set; }

}

以下实施:

   using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
    {
        var resp = reader.ReadToEnd();
        var serializer = new JavaScriptSerializer();
        var obj = serializer.Deserialize<BigCenterResponse>(resp);
        obj.Responses = serializer.Deserialize<List<Result>>(resp);
        return obj;
    }

我能够正确设置IsError,但响应不会被填充。我尝试过反序列化BigCenterResponse并尝试单独反序列化结果部分(如上所示)。似乎都没有用。

1 个答案:

答案 0 :(得分:0)

JavaScriptSerializer不使用DataMemberDataContract属性。但它不区分大小写。因此public int type { get; set; }public int Type { get; set; }

之间没有区别
public class Message
{
    public int Type { get; set; }
    public string Text { get; set; }
}

public class Result
{
    public bool IsError { get; set; }
    public List<Message> Messages { get; set; }
}

public class BigCenterResponse
{
    public List<Result> Results { get; set; }
    public bool IsError { get; set; }
    public string SessionId { get; set; }
}