Metro App - 反序列化 JSON 字符串

本文关键字:JSON 字符串 反序列化 App Metro | 更新日期: 2023-09-27 18:33:11

我想反序列化我从网络服务获得的 JSON 字符串。我的问题是,反序列化的对象类数组(Result类型)中始终有0个项目。

但 Web 服务返回正确的字符串。所以我认为失败发生在我如何反序列化字符串/流的方式上。

知道我的错是什么吗?

//JSON result string:
{"Results":
    [{"Result":{
     "Name":"Rechnung2",
     "Date1":"2012-10-05",
     "Item1":"50",
     "Item2":"10",
     "CompanyName":"Contoso",
     "Description":"My description"}}]
}    

[DataContract]
public class Result
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string Date1 { get; set; }
    [DataMember]
    public string Item1 { get; set; }
    [DataMember]
    public string Item2 { get; set; }
    [DataMember]
    public string CompanyName { get; set; }
    [DataMember]
    public string Description { get; set; }
}
public async void GetjsonStream()
    {
        HttpClient client = new HttpClient();
        string url = "http://localhost/test/api.php?format=json&key=12345";
        HttpResponseMessage response = await client.GetAsync(url);
        //ReadAsStringAsync() works fine, so I think ReadAsStreamAsync() works also fine
        var str = await response.Content.ReadAsStreamAsync();
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Result[]));
        //Result has always 0 items
        Result[] res = (Result[])ser.ReadObject(str);
    }

Metro App - 反序列化 JSON 字符串

我自己没有使用过DataContractJsonSerializer,所以这可能不是最好的方法 - 但我怀疑问题是 JSON 表示"包含结果集合的对象" - 而不是"结果集合"。

除了现有代码之外,请尝试以下操作:

[DataContract]
public class ResultCollection
{
    [DataMember]
    public Result[] Results { get; set; }
}
...
var ser = new DataContractJsonSerializer(typeof(ResultCollection));
var collection = (ResultCollection)ser.ReadObject(str);
var results = collection.Results;

如果有帮助,您也可以将Results类型更改为List<Result>

(我刚刚尝试了上面的代码,它给了我正确的结果,所以看起来这至少是正确的......