unity c# - 如何获取列表的值<object>

unity c# - how to get values of list<object>

我有这个json:

[
  [
    [
      "Tel Aviv",
      "Beersheba",
      "Jerusalem",
      "Haifa"
    ]
  ],
  [
    {
      "City": "Tel Aviv"
    },
    {
      "City": "Beersheba"
    },
    {
      "City": "Jerusalem"
    },
    {
      "City": "Haifa"
    },
    {
      "City": "Jerusalem"
    },
    {
      "City": "Tel Aviv"
    },
    {
      "City": "Haifa"
    },
    {
      "City": "Beersheba"
    },
    {
      "City": "Jerusalem"
    },
    {
      "City": "Jerusalem"
    },
    {
      "City": "Haifa"
    },
    {
      "City": "Tel Aviv"
    },
    {
      "City": "Tel Aviv"
    },
    {
      "City": "Beersheba"
    }
  ]
]

然后我将其转换为列表:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft;
string jsonStr = "<json string from above>";
List<object> data;
private void Start()
{
    data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<object>>(jsonStr);
    Debug.Log(data[0,0]);
}

但是当调试器到达 "Debug.Log(data[0,0]);" 它打印:

Severity Code Description Project File Line Suppression State Error CS0021 Cannot apply indexing with [] to an expression of type 'object' Assembly-CSharp C:\Users\cdi2\Downloads\mdClone-20180627T083334Z-001\mdClone\Assets\CreateTable.cs 31 Active

您的字符串被反序列化为 List<object> 列表只能用一维索引。
所以反序列化只创建了两个 JArray 类型的对象。
第一个是4个城市的组,第二个是14个城市的数组

你可以用

得到第一个对象的第一个元素
Console.WriteLine((data[0] as JArray)[0][0]);

同时,如果您想访问第二个 JArray 中的任何元素,您可以使用此语法

Console.WriteLine((data[1] as JArray)[1]["City"]);   // Beersheba