I tried to print all of the sub keys in "items" from json file(shown below), but getting an invalid cast exception on this line:
foreach (KeyValuePair<string, JToken> sub in (JObject)obj2["items"])
I have no idea why it keeps showing this error.
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class JsonReader : MonoBehaviour
{
[SerializeField]
public string filePath;
[ContextMenu("Load Data")]
private void LoadData()
{
JObject obj2 = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(filePath));
foreach (KeyValuePair<string, JToken> sub in (JObject)obj2["items"])
{
Debug.Log(sub.Key);
}
}
}
JSON File Content
{
"items": [
{
"id": "143675",
"item": "Action Figure",
"name": "Goku",
"color": "Orange"
},
{
"id": "258943",
"item": "Water Bottle",
"name": "Pcares",
"color": "Silver"
},
{
"id": "326824",
"item": "White Board",
"name": "Boardy",
"color": "White"
},
{
"id": "423168",
"item": "Monitor",
"name": "Dell",
"color": "Black"
}
]
}
I want the expected output to show all of the keys so like:
id
item
name
color
Any help would be appreciated!