将 JSON 数组反序列化为强类型 .NET 对象 [英] Deserializing JSON array into strongly typed .NET object

查看:28
本文介绍了将 JSON 数组反序列化为强类型 .NET 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我可以调用第 3 方 api 并取回单个类的数据时,使用此代码一切都可以正常反序列化

When I can call the 3rd party api and get back a single class worth of data everything deserialises fine using this code

TheUser me = jsonSerializer.Deserialize(response, typeof(TheUser)) as TheUser

当我尝试反序列化作为数组的 JSON 响应内容时出现问题,例如

The problem comes when I try and deserialise JSON response content that is an array, such as

{
   "data": [
      {
         "name": "A Jones",
         "id": "500015763"
      },
      {
         "name": "B Smith",
         "id": "504986213"
      },
      {
         "name": "C Brown",
         "id": "509034361"
      }
   ]
}

如果我在数据"成员周围使用自定义包装类,并且该成员需要是 List 类型,我才能使序列化工作.如果将它们作为 List 类型,我会从 JsonParser DesializeType 方法中得到 ArgumentException.

I can only get the serialization to work if I use a custom wrapping class around the "data" member and that member needs to be of type List<object>. If it have them as type List<TheUser> I get ArgumentException from the JsonParser DesializeType method.

我最初尝试在没有这样的包装类型的情况下进行序列化

I originally tried to serialise without a wrapping type like this

List<TheUser> freinds = jsonSerializer.Deserialize(response, typeof(List<TheUser>)) as List<TheUser>;

但这只会返回一个空集合.当然,我必须能够将数组反序列化为强类型列表.

but that just returns me an empty collection. Surely I must be able to have the array deserialize to a strongly typed list.

推荐答案

Afer 看 ,对于 WP7 Hammock 实际上并不使用 Json.Net 进行 JSON 解析.相反,它使用自己的解析器,不能很好地处理自定义类型.

Afer looking at the source, for WP7 Hammock doesn't actually use Json.Net for JSON parsing. Instead it uses it's own parser which doesn't cope with custom types very well.

如果直接使用 Json.Net,则可以反序列化为包装对象内的强类型集合.

If using Json.Net directly it is possible to deserialize to a strongly typed collection inside a wrapper object.

var response = @"
    {
        ""data"": [
            {
                ""name"": ""A Jones"",
                ""id"": ""500015763""
            },
            {
                ""name"": ""B Smith"",
                ""id"": ""504986213""
            },
            {
                ""name"": ""C Brown"",
                ""id"": ""509034361""
            }
        ]
    }
";

var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass));

return des.data.Count.ToString();

并与:

public class MyClass
{
    public List<User> data { get; set; }
}

public class User
{
    public string name { get; set; }
    public string id { get; set; }
}

必须使用 data 属性创建额外的对象很烦人,但这是 JSON 格式对象构造方式的结果.

Having to create the extra object with the data property is annoying but that's a consequence of the way the JSON formatted object is constructed.

文档:序列化和反序列化 JSON

Documentation: Serializing and Deserializing JSON

这篇关于将 JSON 数组反序列化为强类型 .NET 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆