- Home /
How to get a JSON string of a folder structure with c# in Unity3d
Hello,
i am willing to generate a json string containing the structure of a given folder, searching where to start, i found that is easy using .NET but i don't know why i didn't get it in unity, maybe it is obvious, but excuse me for this if so, i am just a beginner. Thank you.
I don't see how this json would look like, you could say that every folder would be an array of files, names of the folders and files would be keys in the json but what would be their values?
the name of files type i want to fetch, for instance if i am into pngs i will affect the names of png files as list or something...
Answer by Aziz1989 · Jul 07, 2015 at 12:47 PM
Hi again,
i managed to code this:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding.Serialization.JsonFx;
using System.IO;
public class JBrowser : MonoBehaviour
{
private string title ;
private bool isFolder ;
private string key ;
private List<string> children;
private DirectoryInfo fsi;
private StreamWriter streamWriter;
private bool on = true;
void Start ()
{
fsi = new DirectoryInfo (@"c:\");
title = fsi.Name;
Debug.Log (title);
children = new List<string> ();
}
void Update ()
{
if (on) {
if (fsi.Attributes == FileAttributes.Directory) {
isFolder = true;
foreach (FileSystemInfo f in fsi.GetFileSystemInfos()) {
children.Add (f.Name.ToString ());
}
} else {
isFolder = false;
}
key = title.Replace (" ", "").ToLower ();
// JsonToDynatree ();
// }
//
//
// private void JsonToDynatree ()
// {
string data = JsonWriter.Serialize (children);
// if(!Directory.Exists(PATH)){
// Directory.CreateDirectory(PATH);
// }
streamWriter = new StreamWriter (@"c:\JsonBrowsingList.txt");
streamWriter.Write (data);
streamWriter.Close ();
// return JsonConvert.SerializeObject (this, Formatting.Indented);
on = false;
}
}
}
and i ve created the json.txt file in the c:/ drive, and it is supposed to be filled with the folders and files names but instead is only showing empty brackets... ?? ([])
Answer by Bomanden · Apr 28, 2018 at 11:14 AM
Old question, but maybe others will land here, (Have a look at this post) https://stackoverflow.com/questions/24725775/converting-a-directory-structure-and-parsing-to-json-format-in-c-sharp
Just change out to your preferred parser.
public string JsonToDynatree()
{
//return JsonConvert.SerializeObject(this, Formatting.Indented);
return JsonUtility.ToJson(this, true);
}