0

I have this 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"
    }
  ]
]

And i converted it to a List:

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]);
}

But when the dubugger got to "Debug.Log(data[0,0]);" it printed:

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

2
  • And what do you expect it to print? Commented Jul 1, 2018 at 9:01
  • the first value: "Tel Aviv" Commented Jul 1, 2018 at 9:08

1 Answer 1

2

Your string is deserialized in a List<object> A list can be indexed with only one dimension.
So the deserialization creates only two objects of type JArray.
The first one is the group of four cities and the second one is an array of 14 cities.

You can get the first element of the first object with

Console.WriteLine((data[0] as JArray)[0][0]);

While, if you want to reach any of the elements in the second JArray you can use this syntax

Console.WriteLine((data[1] as JArray)[1]["City"]);   // Beersheba
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.