new to JSON - one line in JSON = one object?

Hello guys i please need your help.
I am trying to make most simple way to bulk import my items in stock to my List in my object and want try it using JSON but i cant figure how to do it.

So i have my object Hardwares with List i want add to this list by json so i did this :
C#:

     public void ImportHardware()
        {
            if(SaveManager.ImportExist())
            {
                    string jsonHW = File.ReadAllText(Application.streamingAssetsPath + "/import/import.json");
                    Hardware newHW = JsonUtility.FromJson<Hardware>(jsonHW);
                    Debug.Log(newHW.imei);
            }
            Debug.Log("Import Hardware");
        }

JSON:

{"type":1,"currentStock":"MIG_UPC","productCode":"FIXUPCTEL","owner":"FREE","state":0,"imei":"testjson1","returnOrder":""}

This is working as intended but i want put to this json file more of this hardware objects and then somhow add this objects in foreach loot to my Hardwares objects.
Is it possible?
Something like this :
c#

   foreach(/*One line in JSON string*/)
                {
                    hardwares.hardwareList.Add(/*this line as object Hardware*/);
                }

JSON

{"type":1,"currentStock":"MIG_UPC","productCode":"FIXUPCTEL","owner":"FREE","state":0,"imei":"testjson1","returnOrder":""}
{"type":1,"currentStock":"MIG_UPC","productCode":"FIXUPCTEL","owner":"FREE","state":0,"imei":"testjson2","returnOrder":""}
{"type":1,"currentStock":"MIG_UPC","productCode":"FIXUPCTEL","owner":"FREE","state":0,"imei":"testjson3","returnOrder":""}

Do you guys have idea if this is possible? Thanks for help

JSON is object-centric, so your second example has a series of three blobs of data on separate lines, and that lives outside of JSON’s ability to organize.

You could instead make a single array of those types of objects, then JSON that, but pretty sure Unity cannot do bare JSON arrays like that. It can only do single objects.

Problems with Unity “tiny lite” built-in JSON:

In general I highly suggest staying away from Unity’s JSON “tiny lite” package. It’s really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes and ALL properties.

Instead grab Newtonsoft JSON .NET off the asset store for free, or else install it from the Unity Package Manager (Window → Package Manager).

Also, always be sure to leverage sites like:

https://csharp2json.io

PS: for folks howling about how NewtonSoft JSON .NET will “add too much size” to your game, JSON .NET is like 307k in size, and it has the important advantage that it actually works the way you expect a JSON serializer to work in the year 2021.

Thank you for quick reply , i downloaded this package but it says this error.I downloaded JSON before to VS.

Multiple precompiled assemblies with the same name Newtonsoft.Json.dll included on the current platform. Only one assembly with the same name is allowed per platform. (E:/Mega/UnityProjects/Hardware/Hardware/Library/PackageCache/com.unity.nuget.newtonsoft-json@2.0.0/Runtime/Newtonsoft.Json.dll)

I am not rly sure what package i should delete now.

Then you already had the package installed I guess. Just uninstall the one you added. You can also hand edit the Packages/manifest.json to see what is in it.

Please consider using proper industrial-grade source control in order to guard and protect your hard-earned work.

Personally I use git (completely outside of Unity) because it is free and there are tons of tutorials out there to help you set it up as well as free places to host your repo (BitBucket, Github, Gitlab, etc.).

As far as configuring Unity to play nice with git, keep this in mind:

Here’s how I use git in one of my games, Jetpack Kurt:

Using fine-grained source control as you work to refine your engineering:

Share/Sharing source code between projects:

Setting up the right .gitignore file:

Generally setting Unity up (includes above .gitignore concepts):

It is only simple economics that you must expend as much effort into backing it up as you feel the work is worth in the first place.

“Use source control or you will be really sad sooner or later.” - StarManta on the Unity3D forum boards

1 Like

Well, JSON itself does not care about lines. New line characters just count as whitespace. From a pure strutural point of view you would need an array that contains your objects. However there’s a small catch: Unity’s JsonUtility does only support an object as root element. So in order to had an array of objects, this array need to be a field of an object.

So technically, an array of objects would look like this:

[
    {   },
    {   },
    {   }
]

Is order to be able to load it with the JsonUtility you have to do something like:

{
    "data": [
        {   },
        {   },
        {   }
    ]
}

While it’s possible to save json without even a single new line character, when the file should be human editable / readable I would highly recommend to not store a compex object in a single line.

Of course in order to parse the json in my second examples you need another class that represents the root object

[System.Serializable]
public class HardwareList
{
    public List<Hardware> data;
}

So if your file structure looks like I’ve shown you can parse the whole file as one “HardwareList” object. It’s “data” member will contain all the “Hardware” instances.

2 Likes
}   
    "stocks":["FREE","ALL","A11","S35","MIG_UPC"],   
        "productCodes":["CP2SINEW","CP2DBNEW","VFSTB2ENT","VFSTB2PREM","ARDB2NEW","FIXUPCTEL"]
}

If i get what you’ve trying to accomplish right, the thing that you are looking for is what you helped me with in those threads:

Pay attention to the “final” version of the script in the first link (don’t forget to apply the fixes provided by kdgalla). If i’ve understood you correctly, something akin to that would be a solution to your problem.

However my case is not automated in a sense that you have to manually add entries rather than use a for loop. If i understand you correctly, you want to “automatically” get all the JSON entries as a List of Objects, right?

1 Like

Ok ty, i will check that, i want put values manually to json and my program will check if in specific folder is file for import and if yes then will add those objects from json to my already existing list.I want thisbecause after build i want be able to add new objets to program without need of update and touch code and i am lazy do ui for it :smile:

If you are fine with “manually” adding the Object to the List then what is in those links might help you. I also assume that it might be easily tweaked into “building” the objects and adding them to the list through a for loop as well. I advise using https://github.com/jilleJr/Newtonsoft.Json-for-Unity for better multiplatform compatibility (it’s an upgraded version of Newtonsoft.Json that is widely used). The code in the links relies on this library.
If you get any questions on my snippets, feel free to ask. I have spent way too much time trying to figure this out as a newbie :).

1 Like

Also, the answer for the title of your thread would be: one line in JSON is just one line in JSON. :slight_smile:
You can build your constructor out of any elements that you want, you may even use two different deserialized JSONs in one constructor, use the unrelated to your JSON file data (e.g have 2 values coming from JSON and assign an unrelated value as you create a new object of constructors type) and much more!

1 Like

Thank you guys for help.This is solution i wanted :

C#

    public void ImportHardware()
        {
            if(SaveManager.ImportExist())
            {
                string jsonHW = File.ReadAllText(Application.streamingAssetsPath + "/import/import.json");               
                Import newHW = JsonUtility.FromJson<Import>(jsonHW);
                foreach(Hardware hw in newHW.hardwares)
                {
                    hardwares.hwList.add(hw);
                }
            }
        }

JSON

{  
    "hardwares":
[
{"type":1,"currentStock":"MIG_UPC","productCode":"FIXUPCTEL","owner":"FREE","state":0,"imei":"testjson1","returnOrder":""},
{"type":1,"currentStock":"MIG_UPC","productCode":"FIXUPCTEL","owner":"FREE","state":0,"imei":"testjson2","returnOrder":""}
]          
}