How to read .json file

Hi, I have data in .json file.I am looking for ways to parse it in c#.

My json contains data like this,

{"howManyToSpawn":1,"positions":[1],"difficulty":0}
{"howManyToSpawn":1,"positions":[0],"difficulty":1}
1 Like
1 Like

Since the docs donā€™t explain well how to parse anything other than simple flat list, Iā€™m posting this example for others:

Employees.json

{
  "employees":
  [
    {
      "firstName": "John",
      "lastName": "Doe"
    },
    {
      "firstName": "Anna",
      "lastName": "Smith"
    },
    {
      "firstName": "Peter",
      "lastName": "Jones"
    }
  ]
}

Employee.cs

[System.Serializable]
public class Employee
{
    //these variables are case sensitive and must match the strings "firstName" and "lastName" in the JSON.
    public string firstName;
    public string lastName;
}

Employees.cs

[System.Serializable]
public class Employees
{
    //employees is case sensitive and must match the string "employees" in the JSON.
    public Employee[] employees;
}

JSONReader.cs

using UnityEngine;

public class JSONReader : MonoBehaviour
{
    public TextAsset jsonFile;

    void Start()
    {
        Employees employeesInJson = JsonUtility.FromJson<Employees>(jsonFile.text);

        foreach (Employee employee in employeesInJson.employees)
        {
            Debug.Log("Found employee: " + employee.firstName + " " + employee.lastName);
        }
    }
}
71 Likes

If you can give simple example as this to deserialize JSON for adding it into ScriptObjects. Iā€™d highly appreciate it.

Unity really need to provide simple and straightforward examples like this into their documentation rather than just complex theories.

7 Likes

Many thanks to Brad-Newman for this example!

For any other beginners, to get this to work I did the following:
Create Empty, then attach JSONReader.cs script to it
Create Assets/Resources, and put Employees.json in it
Drag Employees.json to the Json File variable of the JSONReader script

I initially put Employees.json into the StreamingAssets folder, but Unity didnā€™t recognize it as a text file in that location

3 Likes

I modified the code for my app, and figured out how to get it to work from TestRunner:

JsonReader.cs:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;

// give Test Runner access to private variables and methods
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("JsonReaderTest")]

[Serializable]
public class JsonLesson
{
    public string Name;
    //public string[] Words;
}

[System.Serializable]
public class JsonLessonList
{
    // jsonLessonList is case sensitive and must match the string "jsonLessonList" in the JSON.
    public JsonLesson[] jsonLessonList;
}



public class JsonReader : MonoBehaviour
{
    //=================== Set from Unity editor =======================
    // file to read lessons from
    public TextAsset jsonFile;

    //=================== MonoBehavior interface =======================
    void Start()
    {

        lessonList = LoadLessonFromFile();
    }

    //======================= public API =================================


    // create one instance of the TrialController for the app
    private static JsonReader jsonReader;
    public static JsonReader Instance()
    {
        if (!jsonReader)
        {
            jsonReader = FindObjectOfType(typeof(JsonReader)) as JsonReader;

            if (!jsonReader)
            {
                Debug.LogError("JsonReader inactive or missing from unity scene.");
            }
        }

        return jsonReader;
    }

    //============= internal structures and methods ======================

    // Make result of json read available to test runner
    internal JsonLessonList lessonList;


    internal JsonLessonList LoadLessonFromFile()
    {
        Assert.IsNotNull(jsonFile);

        JsonLessonList testLessonList = JsonUtility.FromJson<JsonLessonList>(jsonFile.text);

        foreach (JsonLesson lesson in testLessonList.jsonLessonList)
        {
            Debug.Log("Found lesson: " + lesson.Name);
        }

        return testLessonList;
    }
}

JsonReaderTest.cs:

using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;

namespace Tests
{
    public class JsonReaderTest
    {
        // create instance for test
        JsonReader jsonReader;

        //JsonLessonList jsonLessonList;

        [SetUp]
        public void Setup()
        {
            jsonReader = new GameObject().AddComponent<JsonReader>();
            jsonReader.jsonFile = Resources.Load("lesson-test") as TextAsset;
        }

        [TearDown]
        public void Teardown()
        {
            Object.Destroy(jsonReader);
        }

        // Verify class exists
        [Test]
        public void JsonReaderClassExists()
        {
            Assert.IsNotNull(jsonReader);
            Assert.IsNotNull(jsonReader.jsonFile);
        }

        [UnityTest]
        public IEnumerator TestStart()
        {
            Assert.Pass("PASS, ignore stack trace");

            yield return null;
        }

        [Test]
        public void TestFileParsesOkTest()
        {
            JsonLessonList testLessonList = jsonReader.LoadLessonFromFile();

            // NullReferenceException here is often caused by an error in the test file itself,
            // check that field names match the structure
            Assert.IsNotNull(testLessonList);
        }

    }
}

lesson-test.json

{
  "jsonLessonList":
  [
    {
      "Name": "lesson-test1"
    },
    {
      "Name": "lesson-test2"
    }
  ]
}
1 Like

Hey
if I run ur JsonReader.cs with the same json file, it gives my and error:

ArgumentException: JSON parse error: The document root must not follow by other values.
UnityEngine.JsonUtility.FromJson (System.String json, System.Type type) (at <1386288601af43018501cce2912f52f4>:0)
UnityEngine.JsonUtility.FromJson[T] (System.String json) (at <1386288601af43018501cce2912f52f4>:0)
JsonReader2.LoadLessonFromFile () (at Assets/JsonReader2.cs:69)
JsonReader2.Start () (at Assets/JsonReader2.cs:36)

Yep, Iā€™m getting the same thing. jsonFile.text can be accessed fine as a string, but for some reason JsonUtility.FromJson(jsonFile.text) refuses to ā€˜readā€™ or whatever. Maybe itā€™s a parsing error? I donā€™t see why though, the above example is in perfect JSON format. At least I think it is.

Just figured out my issue, in case anyone cares. It was because I had comments in my JSON file :sunglasses:ā€¦

1 Like


@tmurraysdca70 @Brad-Newman
How will you write a class for such JSON file where the ā€œpropertiesā€ changes according to the ā€œtypeā€?

This helped me! Thanks for the example man kudos

Hi, Thanks @Brad-Newman .194718 for the code. One question, Reading the data is working fine, but how to update the json file again please. I need to change some values and save back the file.