Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

How to read .json file

Discussion in 'Editor & General Support' started by idurvesh, Apr 30, 2016.

Thread Status:
Not open for further replies.
  1. idurvesh

    idurvesh

    Joined:
    Jun 9, 2014
    Posts:
    495
    Hi, I have data in .json file.I am looking for ways to parse it in c#.

    My json contains data like this,

    Code (CSharp):
    1. {"howManyToSpawn":1,"positions":[1],"difficulty":0}
    2. {"howManyToSpawn":1,"positions":[0],"difficulty":1}
     
    crns13 likes this.
  2. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    9,065
  3. Brad-Newman

    Brad-Newman

    Joined:
    Feb 7, 2013
    Posts:
    185
    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
    Code (JavaScript):
    1. {
    2.   "employees":
    3.   [
    4.     {
    5.       "firstName": "John",
    6.       "lastName": "Doe"
    7.     },
    8.     {
    9.       "firstName": "Anna",
    10.       "lastName": "Smith"
    11.     },
    12.     {
    13.       "firstName": "Peter",
    14.       "lastName": "Jones"
    15.     }
    16.   ]
    17. }
    Employee.cs
    Code (CSharp):
    1. [System.Serializable]
    2. public class Employee
    3. {
    4.     //these variables are case sensitive and must match the strings "firstName" and "lastName" in the JSON.
    5.     public string firstName;
    6.     public string lastName;
    7. }
    8.  
    Employees.cs
    Code (CSharp):
    1. [System.Serializable]
    2. public class Employees
    3. {
    4.     //employees is case sensitive and must match the string "employees" in the JSON.
    5.     public Employee[] employees;
    6. }
    JSONReader.cs
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class JSONReader : MonoBehaviour
    4. {
    5.     public TextAsset jsonFile;
    6.  
    7.     void Start()
    8.     {
    9.         Employees employeesInJson = JsonUtility.FromJson<Employees>(jsonFile.text);
    10.  
    11.         foreach (Employee employee in employeesInJson.employees)
    12.         {
    13.             Debug.Log("Found employee: " + employee.firstName + " " + employee.lastName);
    14.         }
    15.     }
    16. }
     
    Last edited: Jan 9, 2020
  4. pruthv

    pruthv

    Joined:
    Apr 20, 2018
    Posts:
    2

    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.
     
  5. tmurraysdca70

    tmurraysdca70

    Joined:
    May 5, 2020
    Posts:
    4
    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
     
    ssa4910000, Fenikkel and MsMissa17 like this.
  6. tmurraysdca70

    tmurraysdca70

    Joined:
    May 5, 2020
    Posts:
    4
    I modified the code for my app, and figured out how to get it to work from TestRunner:

    JsonReader.cs:
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.Assertions;
    6.  
    7. // give Test Runner access to private variables and methods
    8. [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("JsonReaderTest")]
    9.  
    10. [Serializable]
    11. public class JsonLesson
    12. {
    13.     public string Name;
    14.     //public string[] Words;
    15. }
    16.  
    17. [System.Serializable]
    18. public class JsonLessonList
    19. {
    20.     // jsonLessonList is case sensitive and must match the string "jsonLessonList" in the JSON.
    21.     public JsonLesson[] jsonLessonList;
    22. }
    23.  
    24.  
    25.  
    26. public class JsonReader : MonoBehaviour
    27. {
    28.     //=================== Set from Unity editor =======================
    29.     // file to read lessons from
    30.     public TextAsset jsonFile;
    31.  
    32.     //=================== MonoBehavior interface =======================
    33.     void Start()
    34.     {
    35.  
    36.         lessonList = LoadLessonFromFile();
    37.     }
    38.  
    39.     //======================= public API =================================
    40.  
    41.  
    42.     // create one instance of the TrialController for the app
    43.     private static JsonReader jsonReader;
    44.     public static JsonReader Instance()
    45.     {
    46.         if (!jsonReader)
    47.         {
    48.             jsonReader = FindObjectOfType(typeof(JsonReader)) as JsonReader;
    49.  
    50.             if (!jsonReader)
    51.             {
    52.                 Debug.LogError("JsonReader inactive or missing from unity scene.");
    53.             }
    54.         }
    55.  
    56.         return jsonReader;
    57.     }
    58.  
    59.     //============= internal structures and methods ======================
    60.  
    61.     // Make result of json read available to test runner
    62.     internal JsonLessonList lessonList;
    63.  
    64.  
    65.     internal JsonLessonList LoadLessonFromFile()
    66.     {
    67.         Assert.IsNotNull(jsonFile);
    68.  
    69.         JsonLessonList testLessonList = JsonUtility.FromJson<JsonLessonList>(jsonFile.text);
    70.  
    71.         foreach (JsonLesson lesson in testLessonList.jsonLessonList)
    72.         {
    73.             Debug.Log("Found lesson: " + lesson.Name);
    74.         }
    75.  
    76.         return testLessonList;
    77.     }
    78. }
    79.  
    JsonReaderTest.cs:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using NUnit.Framework;
    4. using UnityEngine;
    5. using UnityEngine.TestTools;
    6.  
    7. namespace Tests
    8. {
    9.     public class JsonReaderTest
    10.     {
    11.         // create instance for test
    12.         JsonReader jsonReader;
    13.  
    14.         //JsonLessonList jsonLessonList;
    15.  
    16.         [SetUp]
    17.         public void Setup()
    18.         {
    19.             jsonReader = new GameObject().AddComponent<JsonReader>();
    20.             jsonReader.jsonFile = Resources.Load("lesson-test") as TextAsset;
    21.         }
    22.  
    23.         [TearDown]
    24.         public void Teardown()
    25.         {
    26.             Object.Destroy(jsonReader);
    27.         }
    28.  
    29.         // Verify class exists
    30.         [Test]
    31.         public void JsonReaderClassExists()
    32.         {
    33.             Assert.IsNotNull(jsonReader);
    34.             Assert.IsNotNull(jsonReader.jsonFile);
    35.         }
    36.  
    37.         [UnityTest]
    38.         public IEnumerator TestStart()
    39.         {
    40.             Assert.Pass("PASS, ignore stack trace");
    41.  
    42.             yield return null;
    43.         }
    44.  
    45.         [Test]
    46.         public void TestFileParsesOkTest()
    47.         {
    48.             JsonLessonList testLessonList = jsonReader.LoadLessonFromFile();
    49.  
    50.             // NullReferenceException here is often caused by an error in the test file itself,
    51.             // check that field names match the structure
    52.             Assert.IsNotNull(testLessonList);
    53.         }
    54.  
    55.     }
    56. }
    lesson-test.json
    Code (CSharp):
    1. {
    2.   "jsonLessonList":
    3.   [
    4.     {
    5.       "Name": "lesson-test1"
    6.     },
    7.     {
    8.       "Name": "lesson-test2"
    9.     }
    10.   ]
    11. }
     
    crns13 likes this.
  7. chernobyyl

    chernobyyl

    Joined:
    Aug 7, 2019
    Posts:
    6
    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)
     
  8. owmacohe

    owmacohe

    Joined:
    Feb 6, 2019
    Posts:
    2
    Yep, I'm getting the same thing. jsonFile.text can be accessed fine as a string, but for some reason JsonUtility.FromJson<Employees>(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.
     
  9. owmacohe

    owmacohe

    Joined:
    Feb 6, 2019
    Posts:
    2
    Just figured out my issue, in case anyone cares. It was because I had comments in my JSON file :cool:...
     
    calbond likes this.
  10. kaliAJ

    kaliAJ

    Joined:
    Sep 29, 2018
    Posts:
    18
    upload_2021-2-2_17-48-16.png
    @tmurraysdca70 @Brad-Newman
    How will you write a class for such JSON file where the "properties" changes according to the "type"?
     
    Last edited: Feb 2, 2021
  11. faithmorante

    faithmorante

    Joined:
    Mar 10, 2022
    Posts:
    1
    This helped me! Thanks for the example man kudos
     
  12. imdadahmadmian

    imdadahmadmian

    Joined:
    Oct 13, 2017
    Posts:
    3
    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.
     
    Last edited: Dec 7, 2022
Thread Status:
Not open for further replies.