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}
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}
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);
}
}
}
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.
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
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"
}
]
}
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 ā¦
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.