根级别的数据无效:尝试反序列化json字符串

时间:2022-07-19 18:33:41

I'm using Asp.Net, and although I've done some work deseriaizing Xml before, I've not got to do the same with json.

我正在使用Asp.Net,虽然我之前已经完成了一些去处理Xml的工作,但我没有必要对json做同样的事情。

The error I'm getting is Data at root level is invalid, something I've seen before with Xml deserialization.

我得到的错误是根级别的数据是无效的,我之前看到的Xml反序列化。

Here's the documentation I have for the response:

这是我对回复的文档:

HTTP ResponseCode: 200
HTTP Status: OK
HTTP Body:
{
“Status”:”Success”,
“Response”:”0”,
“Price”:”10.00”,
“BuyerId”:999,
“BuyerContractId”:9999,
“Detail”:”https://...”
}

I'm using a WebClient to get the data back:

我正在使用WebClient来获取数据:

response = wc.UploadString(info.Endpoint, info.Data);

"response" is a string. I use this method to deserialize:

“response”是一个字符串。我使用此方法反序列化:

    public static T JsonResponse<T>(string response)
       where T : class
    {
        var s = new DataContractJsonSerializer(typeof(T));

        using (var r = XmlReader.Create(new StringReader(response)))
        {
            return (T)s.ReadObject(r);
        }
    }

The class I'm trying to deserialize to is:

我正在尝试反序列化的类是:

[DataContract]
public class ResponseProps
{
    [DataMember(Name = "Status")]
    public string Status { get; set; }

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

    [DataMember(Name = "Price")]
    public decimal Price { get; set; }

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

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

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

Here's how it's called:

以下是它的名称:

var cr = XmlHelper.JsonResponse<ResponseProps>(response);

Anyone got any clues as to where I'm going wrong?

任何人都有任何关于我哪里出错的线索?

1 个解决方案

#1


2  

Assuming the data comes in JSON format, I changed the following -

假设数据是JSON格式,我更改了以下内容 -

public static T JsonResponse<T>(string response)
   where T : class
    {
        return JsonConvert.DeserializeObject<T>(response);
    }

Now this works fine-

现在这很好 -

var q = JsonResponse<ResponseProps>('jsonString');

#1


2  

Assuming the data comes in JSON format, I changed the following -

假设数据是JSON格式,我更改了以下内容 -

public static T JsonResponse<T>(string response)
   where T : class
    {
        return JsonConvert.DeserializeObject<T>(response);
    }

Now this works fine-

现在这很好 -

var q = JsonResponse<ResponseProps>('jsonString');