将具有数组的对象转换为仅数组

时间:2017-08-21 09:20:40

标签: c# arrays json

所以我有一个问题,在反序列化之后,我的JSON转换为一个对象(没有别的办法)。在我的对象中有另一个名为" Content"的对象。

这个对象包含一个数组,但由于这也需要转换为一个对象,因此它出现了:

object Content = {[
      {
        "geofence_id": 44896,
        "name": "WAAAAAAAAAAAAA"
      },
      {
        "geofence_id": 44920,
        "name": "Work"
      }
    ]}

(这也是其他方式)。

现在我想知道如何将此对象转换为对象数组。

我试过了:

GeofenceResponse[] arr = Content as GeofenceResponse[];

其中content.Content是顶部片段中显示的对象,GeofenceResponse []是objectarray。

但这导致arr为空。

GeofenceResponse看起来像这样:

class GeofenceResponse : Response
{
    public int Geofence_id { get; set; }
    public string Name { get; set; }
}

答案只是:

class Response
{
}

因为我有多个不同的。

但我在Contect对象中得到了多个。

2 个答案:

答案 0 :(得分:0)

您的JSON似乎无效{[...]}无效http://www.json.org/ BTW有效的数据对象包装是{" content":[...]}

您不应该将数组包装到对象中,而是直接反序列化数组:

string json = @"[
  {
    'Name': 'Product 1',
    'ExpiryDate': '2000-12-29T00:00Z',
    'Price': 99.95,
    'Sizes': null
  },
  {
    'Name': 'Product 2',
    'ExpiryDate': '2009-07-31T00:00Z',
    'Price': 12.50,
    'Sizes': null
  }
]";
List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);

取自https://www.newtonsoft.com/json/help/html/SerializingCollections.htm

的样本

答案 1 :(得分:0)

管理自己找到答案,我所要做的就是:

GeofenceResponse[] arr = JsonConvert.DeserializeObject<GeofenceResponse[]>(content.Content.ToString(), jsonSettings);

这导致完美填充的GeofenceResponses数组