Page 1 sur 1

[Résolu] Modifié valeur Json

Publié : 01 Oct 2020 16:11
par Leuprochon
Bonjour à tous !

J'expérimente VisionLib qui est très sympa et j'aimerais modifier un paramètre qui se trouve dans un fichier .vl (json schema ):

https://visionlib.com/2020/04/02/vision ... se-20-3-1/
(partie Json Schema)

Je n'ai pas très bien compris comment fonctionné le script avec du json

Il me faut juste passer une valeur de false à true et de true à false selon les cas.

Merci beaucoup !

Re: Modifié valeur Json

Publié : 09 Oct 2020 11:13
par Leuprochon
Bon, alors j'ai un peu avancé mais ça ne fonctionne toujours pas

J'arrive à lire mon fichier, à le modifier, à le sauvegarder. Ou est le problème me direz vous ? Ben il ne prend pas en compte ma modification, allez savoir pourquoi ...

Voici mon fichier .vl (équivalent au .txt)

Code : Tout sélectionner

 {
      "type": "VisionLibTrackerConfig",
      "version": 1,
      "meta": {
        "author": "",
        "description": "",
        "name": "",
        "vlTrackingConfig": {},
        "uuid": "2bcc7e7f-6220-4a6a-af5b-166b7afd17c6",
        "timeCreated": 1601545823,
        "timeChanged": 1601545825
      },
      "tracker": {
        "type": "modelTracker",
        "version": 1,
        "parameters": {
          "minInlierRatioInit": 0.6,
          "minInlierRatioTracking": 0.42,
          "laplaceThreshold": 1,
          "normalThreshold": 2.5,
          "lineGradientThreshold": 40,
          "lineSearchLengthInitRelative": 0.04125,
          "lineSearchLengthTrackingRelative": 0.03125,
          "keyFrameDistance": 50,
          "metric": "cm",
          "showLineModel": true,
          "models": [
            {
              "name": "Gaio_ModelTarget_V01",
              "uri": "project_dir:Gaio_ModelTarget_V01.fbx"
            }
          ],
          "initPose": {
            "t": [
              -7.307137489318848,
              37.529937744140625,
              299.53997802734375
            ],
            "q": [
              0.995162308216095,
              0.09824426472187042,
              0,
              0
            ]
          }
        }
      }
    }
Et voici mon code

[*][*]

Code : Tout sélectionner

  using System.Collections;
        using System.Collections.Generic;
        using UnityEngine;
        using System.IO;
        using SimpleJSON;
        
    public class ChangeJsonValue : MonoBehaviour
    {
        string path;
        string jsonString;
    
        // Start is called before the first frame update
        void Start()
        {
            path = Application.dataPath + "/StreamingAssets/VisionLib/Gaio/test.vl";
            jsonString = File.ReadAllText(path);
    
            JSONNode data = JSON.Parse(jsonString);
            
            foreach (JSONNode record in data["tracker"])
            {
                record["showLineModel"] = false;
                Debug.Log(record["showLineModel"]);
            }
    
            
        }
    
        private void Update()
        {
            File.WriteAllText(Application.dataPath + "/StreamingAssets/VisionLib/Gaio/sdsd.vl", jsonString);
        }
    }

Dans la console d'unity le changement s'effectue bien, mais quand je vérifie sur mon nouveau fichier il n'y a aucune modification. Je ne comprends pas pourquoi.

Si quelqu'un a une idée ça serait super !

Merci bien

Re: Modifié valeur Json

Publié : 09 Oct 2020 11:40
par boubouk50
A aucun moment tu ne modifies ta JsonString, tu ne modifies que les données récupérées.
Il te faut donc recréer la JsonString avec les données modifiées.
Heureusement, c'est très simple avec la fonction ToJson ().
Juste avant de sauvegarder, hop tu mets à jour ta chaîne de caractères et ça devrait être bon.

Code : Tout sélectionner

jsonString = JsonUtility.ToJson (data, true);
Je vois que n'utilises pas non plus la classe JsonUtility pour importer, mais un namespace supplémentaire. Sache que c'est intégré et ça fait la même chose.

Re: Modifié valeur Json

Publié : 09 Oct 2020 14:24
par Leuprochon
Merci pour ton aide !

Malheureusement ça ne veut pas fonctionner.

Voici mon code now:

Code : Tout sélectionner

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using SimpleJSON;

public class ChangeJsonValue : MonoBehaviour
{
    string path;
    string jsonString;

    // Start is called before the first frame update
    void Start()
    {
        path = Application.dataPath + "/StreamingAssets/VisionLib/Gaio/test.vl";
        jsonString = File.ReadAllText(path);

        JSONNode data = JSON.Parse(jsonString);

        foreach (JSONNode record in data["tracker"])
        {
            record["showLineModel"] = false;
           
        }
        Debug.Log(JsonUtility.ToJson(data, true));
        Debug.Log(data);
        Save();




    }

    private void Save()
    {
        File.WriteAllText(Application.dataPath + "/StreamingAssets/VisionLib/Gaio/sdsd.vl", jsonString);
    }
}
Dans la console unity j'ai

Pour le Debug.Log(JsonUtility.ToJson(data, true)); = {}
Pour le Debug.Log(data); = tout mon fichier texte donc j'ai bien toutes mes données dans data

Je ne comprends pas pourquoi quand il recréé mes données il n'y arrive pas et il réécrit {} sans rien d'autre ... Comme si il n'arrivait pas à récupérer les données de data. On obtient donc un fichier vierge

Re: Modifié valeur Json

Publié : 09 Oct 2020 15:26
par boubouk50
Je ne sais pas ce que JSONNODE contient et comment il est géré.

Perso, j'utilise la classe JsonUtility pour récupérer et envoyer les données.

Mon Json:

Code : Tout sélectionner

{
	"n_name": "myMainName",
	"dimension": { "x": 2.5346, "y": 1.192 },
	"datas": [
		{
			"s_name": "mySecondaryName1",
			"position": { "x": 0.168, "y": 0.592 }
		},
		{
			"s_name": "mySecondaryName2",
			"position": { "x": 0.832, "y": 0.592 }
		},
		etc...
	]
}
j'ai les classes qui définissent les éléments de mon JSON

Code : Tout sélectionner

[Serializable]
public class MainData
{
	public string m_name;
	public Vector2 dimension;
	public List<SecondaryData> datas;
}

[Serializable]
public class SecondaryData
{
	public string s_name;
	public Vector2 position;
}
Ensuite, c'est très simple pour lire et écrire un JSon:

Code : Tout sélectionner

//La lecture
MainData mainData = JsonUtility.FromJson<MainData>(File.ReadAllText(jsonFilePath));
//L'écriture
File.WriteAllText (jsonFilePath, JsonUtility.ToJson (mainData, true));
Entre temps, bien évidemment tu travailles sur mainData pour modifier les données.

Re: Modifié valeur Json

Publié : 10 Oct 2020 22:23
par Leuprochon
Merci pour ton aide !

Au même moment le créateur du SimpleJSON m'a aidé a résoudre mon problème, voici le post pour ceux que ça intéresse :

https://forum.unity.com/threads/modify- ... st-6402034