将二维数组保存为 JSON [英] Saving a 2D array as JSON

查看:55
本文介绍了将二维数组保存为 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将模拟保存到 JSON 文件中.我做一艘移动的船的基础知识.在世界空间中将有一个探测按钮,可提供有关该船的信息.我想将该信息保存到 JSON 中.任何人都知道如何做到这一点.我是 Unity 的新手.在按钮 () 我想保存船舶信息(例如位置、深海、风速、温度、流量

I Have problem to save my simulation into JSON File. the basics I make a moving ship. in the world space there will be a probe button that will provide information about the ship. I want to save that information into JSON. Anyone know how to do that. I am new in Unity. In button () I want to save the ship information (eg. position, depthsea, windspeed, temperature,flow

public class test : MonoBehaviour
{
    // Start is called before the first frame update

    public GameObject Ship;
    public GameObject hole;
    public GameObject turtle;
    public GameObject panelhole;
    public GameObject panelturtle;
    
    public RectTransform shipvalue;
    //public RectTransform flowvalue;
    //public RectTransform windspeedvalue;
    //public RectTransform temperaturevalue;
    //public RectTransform depthvalue;
    public Vector3 offset;
    public RectTransform Basicobject; //parent



    //public static bool captureAllKeyboardInput = false;

    private bool paneloff = false;
    public float duration = 1;

    public int[,] grid = new int[10, 16];
    public float[,] depth = new float[4, 3]
    {{1.6f, 2.3f, 3.5f },
     {4, 5, 6.5f},
     {7, 8, 6.5f},
     {7, 8, 6.5f}};
 
    public float[,] temperaturedata = new float[10, 16]
    {{0,    0,      0,      0,      0,      0,      0,      22.5f,  22.7f,  23,     23.9f,  24,     26.3f,  26.4f,  26.4f,  26.3f},
    {0,     0,      0,      0,      0,      0,      22.8f,  23.2f,  23.8f,  24.4f,  25,     24.3f,  26.5f,  26.5f,  26.5f,  26.6f},
    {0,     0,      0,      0,      0,      22.5f,  23.1f,  24.8f,  25.3f,  25.7f,  0,      0,      26.7f,  26.3f,  26.2f,  26.6f},
    {0,     0,      0,      0,      23.2f,  23.8f,  25.1f,  25.4f,  25.9f,  0,      0,      26.8f,  26.9f,  26.5f,  26.3f,  26.3f},
    {0,     0,      24.5f,  23.3f,  23.9f,  24.5f,  25.7f,  25.6f,  26.8f,  0,      0,      26.9f,  27.1f,  26.6f,  26.4f,  26.4f},
    {0,     24.1f,  23.9f,  24.9f,  25.4f,  25.5f,  25.9f,  27.4f,  27.2f,  0,      0,      27,     27.2f,  26.8f,  26.4f,  26   },
    {27.4f, 27.7f,  27.3f,  26.2f,  26.2f,  25.9f,  27.5f,  27.7f,  27.3f,  0,      26.8f,  27.2f,  27.2f,  26.9f,  26.4f,  26.2f},
    {28.5f, 29,     27.5f,  27.3f,  27.3f,  27.5f,  27.7f,  27.7f,  27.5f,  27.2f,  27.2f,  27.4f,  27.4f,  26.9f,  26.3f,  26.7f},
    {28.5f, 27.6f,  27.1f,  27,     26.5f,  27.6f,  27.6f,  27.6f,  27.7f,  27.4f,  27.8f,  27.7f,  27.7f,  27,     27,     26.6f},
    {28.5f, 27.6f,  25,     27.3f,  26.8f,  27.8f,  27.3f,  27.5f,  28.1f,  27.9f,  28,     27.6f,  27.7f,  26.9f,  27.1f,  26.8f}};


    public float[,] flowdata = new float[10, 16]
 
    {{0,    0,      0,      0,      0,      0,      0,      0.4f,   0.4f,   0.6f,   0.8f,   0.6f,   0.7f,   0.4f,   0.4f,   0.4f},
    {0,     0,      0,      0,      0,      0,      0.3f,   0.5f,   0.5f,   0.8f,   0.8f,   0.8f,   0.6f,   0.6f,   0.5f,   0.5f},
    {0,     0,      0,      0,      0,      0.4f,   0.7f,   0.7f,   0.7f,   0.7f,   0,      0,      0.9f,   0.6f,   0.4f,   0.4f},
    {0,     0,      0,      0,      0.5f,   0.5f,   0.6f,   0.7f,   0.6f,   0,      0,      0.8f,   0.8f,   0.4f,   0.3f,   0.3f},
    {0,     0,      000,    0.7f,   0.6f,   0.5f,   0.7f,   1,      0.8f,   0,      0,      0.9f,   0.5f,   0.3f,   0.1f,   0.3f},
    {0,     0.5f,   0.7f,   0.6f,   0.8f,   0.8f,   1.3f,   0.9f,   0.5f,   0,      0,      0.8f,   0.3f,   0.1f,   0.2f,   0.2f},
    {0.6f,  0.6f,   0.6f,   0.7f,   1.1f,   0.9f,   0.8f,   0.4f,   0.3f,   0,      0.9f,   0.6f,   0.2f,   0.2f,   0.2f,   0.2f},
    {0.4f,  0.4f,   0.5f,   0.5f,   0.3f,   0.4f,   0.3f,   0.2f,   0.4f,   0.2f,   0.8f,   0.3f,   0.2f,   0.2f,   0.2f,   0.1f},
    {000,   0.3f,   0.5f,   0.2f,   0.2f,   0.2f,   0.2f,   0.1f,   0.2f,   0.6f,   0.6f,   0.3f,   0.3f,   0.2f,   0.2f,   0.2f},
    {000,   000,    0.1f,   0.4f,   0.3f,   0.3f,   0.2f,   0.2f,   0.1f,   0.2f,   0.3f,   0.1f,   0.2f,   0.2f,   0.2f,   0.2f}};

    public float[,] windspeeddata = new float[10, 12]
    {{0,0,0,0,0,0,0,4,4,4,3,3},
    {0,0,0,0,0,0,4,5,4,3,3,3},
    {0,0,0,0,0,5,5,5,5,3,0,0},
    {0,0,0,0,4,4,4,4,4,0,0,3},
    {0,0,3,0,4,4,4,4,4,0,0,3},
    {0,4,4,4,4,4,4,4,3,0,0,3},
    {4,4,4,4,4,4,4,3,3,0,3,4},
    {5,4,4,4,4,4,3,3,3,3,4,4},
    {4,4,4,4,4,4,3,3,3,3,4,4},
    {5,4,4,4,4,4,4,4,4,3,3,3}};


    int row, column, num1, num2;
    int p1;
    int p2;

    int[] grid2 = new int[5];
    public Text shiposition = null;
    public Text depthtext = null;
    public Text windspeedtext = null;
    public Text temperaturetext = null;
    public Text flowtext = null;

    //direction = Ship.transform.rotation.z;
    float LastMove;
    float timeIn = 0.5f;
    public Vector3 direction;

    float zvalue;

    [Serializable]
    public class ShipData
    {

        public int grid;
        public float depth;
        public float windspeed;
        public float temperature;

    }

    [SerializeField]
    private ShipData JSON_ShipData = new ShipData();

    public void SaveintoJson()
    {
        string data = JsonUtility.ToJson(JSON_ShipData);
        System.IO.File.WriteAllText(Application.persistentDataPath + "/DataCenter.json", data);
        Debug.Log("Saving as JSON" + JSON_ShipData);
        Debug.Log(Application.persistentDataPath);
    }

    void Start()
    {
        p1 = 9;
        p2 = 0;
        
        grid[p1, p2] = 1;
        panelhole.SetActive(false);
        panelturtle.SetActive(false);
        Debug.Log(grid[p1, p2]);
        Debug.Log(shiposition.transform.position);
       
    }
    // Update is called once per frame




    void Update()
    {
        
        //Debug.Log(Ship.transform.localEulerAngles.z);
        zvalue = Ship.transform.localEulerAngles.z;

        if (Input.GetKeyDown(KeyCode.RightArrow))
        {

            StartCoroutine(Forward());
       }
        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            StartCoroutine(Backward());
        }
        if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            StartCoroutine(Rotate(Vector3.forward, -90, 1.0f));
            Debug.Log(transform.rotation.eulerAngles.z);
        }
       if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            StartCoroutine(Rotate(Vector3.forward, 90, 1.0f));
            Debug.Log(transform.rotation.eulerAngles.z);
        }
         

        if (Time.time - LastMove > timeIn)
        {
            LastMove = Time.time;
           
        }

        if (Input.GetKeyDown(KeyCode.W))
        {
            
                StartCoroutine(Rotate(Vector3.forward, 90, 1.0f));
               // position(grid);
               // depthsea(depth);
           
        }
        if (Input.GetKeyDown(KeyCode.A))
        {
            if (p2 >= 0)
            {
                StartCoroutine(Backward());
                grid[p1, p2] = 0;
                grid[p1, --p2] = 1;
                //position(grid);
                //depthsea(depth);
            }
            else
            {
                Debug.Log("You can't move left!!");
            }
        }
        if (Input.GetKeyDown(KeyCode.D))
        {
            
            // z = 0
            if (p2 <= 12 && zvalue == 0)
            {
                StartCoroutine(Forward());
                grid[p1, p2] = 0;
                grid[p1, ++p2] = 1;
                //position(grid);
                //depthsea(depth);
                Debug.Log(zvalue);
            }
            // z = 270
            else if (p2 <= 12 && zvalue == 270)
            {
                StartCoroutine(Forward());
                grid[p1, p2] = 0;
                grid[++p1, p2] = 1;
               // position(grid);
                //depthsea(depth);
                Debug.Log(zvalue);
            }

            //// z = 180
            else if (p2 <= 12 && zvalue == 180)
            {
                StartCoroutine(Forward());
                grid[p1, p2] = 0;
                grid[p1, --p2] = 1;
               // position(grid);
                //depthsea(depth);
                Debug.Log(zvalue);
            }
            //// z = 90
            else if (p2 <= 12 && zvalue == 90)
            {
                StartCoroutine(Forward());
                grid[p1, p2] = 0;
                grid[--p1, p2] = 1;
               // position(grid);
                //depthsea(depth);
                Debug.Log(zvalue);
            }
            else
            {
                Debug.Log("You can't move right any further!!");
                Debug.Log(Ship.transform.localEulerAngles.z);
            }
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
           
                StartCoroutine(Rotate(Vector3.forward, -90, 1.0f));
                //position(grid);
                //depthsea(depth);
           
        }
        //WebGLInput.captureAllKeyboardInput = false;
    }

    
    private void position(int[,] grid)
    {

        for (int i = 0; i < grid.GetLength(0); i++)
        {
            for (int j = 0; j < grid.GetLength(1); j++)
            {
                if (grid[i, j] == 1)
                {
                   // Debug.Log("x: " + i + " y: " + j + " Grid: " + grid[i, j]);
                   
                    shiposition.text = "X : " + i + " " + "Y : " + j;
                    shiposition.text.ToString();
                    PlayerPrefs.SetString("position", shiposition.text);
                    PlayerPrefs.Save();
                    Debug.Log(shiposition.text);
                    
                }

            }
        }
    }

    public void windspeed(float[,] windspeeddata)
    {
        for (int x = 0; x < windspeeddata.GetLength(0); x++)
        {
            for (int y = 0; y < windspeeddata.GetLength(1); y++)
            {
                if (grid[x, y] == 1)
                {

                    windspeedtext.text = "Windspeed Level :" + windspeeddata[x, y];
                   
                }

            }
        }

    }


    public void temperature(float[,] temperaturedata)
    {
        for (int x = 0; x < temperaturedata.GetLength(0); x++)
        {
            for (int y = 0; y < temperaturedata.GetLength(1); y++)
            {
                if (grid[x, y] == 1)
                {
                    //Debug.Log(temperaturedata[x, y]);
                    temperaturetext.text = "Temperature :" + temperaturedata[x, y] + "C";
                }

            }
        }
    }

    public void flow(float[,] flowdata)
    {
        for (int x = 0; x < flowdata.GetLength(0); x++)
        {
            for (int y = 0; y < flowdata.GetLength(1); y++)
            {
                if (grid[x, y] == 1)
                {

                    flowtext.text = "Flow :" + flowdata[x, y];
                }

            }
        }
    }

    public void depthsea(float[,] depth)
    {
        for (int x = 0; x < depth.GetLength(0); x++)
        {
            for (int y = 0; y < depth.GetLength(1); y++)
            {
                if (grid[x, y] == 1)
                {
                    depthtext.text = "Depth :" + depth[x, y];
                    Debug.Log(depth[x, y]);
                }
       
            }
        }
    }

    public void moveobject()
    {
        
        shipvalue.transform.position = Ship.transform.position;
        //shipvalue.transform.position.y + 0.5f;
        //flowvalue.transform.position = Ship.transform.position;
        //windspeedvalue.transform.position = Ship.transform.position;
        //temperaturevalue.transform.position = Ship.transform.position;
        //depthvalue.transform.position = Ship.transform.position;

    }
    
    public void button()
    {
        
        position(grid);
        depthsea(depth);
        windspeed(windspeeddata);
        temperature(temperaturedata);
        flow(flowdata);
        moveobject();
     

        //value.transform.position = Ship.transform.position;
        //string newposition = JsonUtility.ToJson(shiposition.text);
        //System.IO.File.WriteAllText(Application.persistentDataPath + "PositionData.json", newposition);
        //Debug.Log(shiposition.text);
    }

推荐答案

JSON 导出本身应该这样工作

The JSON export itself should work that way

但是,从不使用 +/" 作为系统文件路径.而是使用 Path.Combine自动插入正确的路径分隔符

However, never use + "/" for system file paths. Rather use Path.Combine which inserts the correct path separator automatically

System.IO.File.WriteAllText(Path.Combine(Application.persistentDataPath, "DataCenter.json", data);

主要问题

您永远不会为 JSON_ShipData 分配任何值,因此您将始终导出具有默认值的 JSON!

You are never assigning any values into the JSON_ShipData so you will always export a JSON with default values!

所以首先你想要的是为位置存储一个 Vector2Int

So first what you want is to store a Vector2Int for the position

[Serializable]
public class ShipData
{
    public Vector2Int position;
    public float depth;
    public float windspeed;
    public float temperature;
}

那么您可能希望在某些地方更新内容,例如

Then you probably would want to update the content at certain places like e.g.

private bool TryGetPosition(int[,] grid, out Vector2Int position)
{
    position = default;

    for (int x = 0; x < grid.GetLength(0); i++)
    {
        for (int y = 0; y < grid.GetLength(1); j++)
        {
            if (grid[x, y] == 1)
            {
                // store into the returned out value
                position = new Vector2Int(x, y);

                shiposition.text = $"X : {x} Y : {y}";
                shiposition.text.ToString();
                PlayerPrefs.SetInt("positionX", position.x);
                PlayerPrefs.SetInt("positionY", position.y);
                PlayerPrefs.Save();
                Debug.Log(shiposition.text);

                return true;
            }
        }
    }

    return false;
}

请注意,这也更有效,因为如果它已经找到了位置,它不会遍历网格的其余部分

Note that this is also more efficient since it doesn't iterate through the rest of your grid if it already has found the position

对您的其他方法重复相同的操作,然后像使用它们一样使用它们

Repeat the same for your other methods and then use them like e.g.

public void button()
{
    // Check if a position is found and if yes update the json data
    if(TryGetPosition(grid, out var position)
    {
        JSON_ShipData.position = position;
    }

    // Repeat the same for your other values

    SaveintoJson();
}


一般注意事项:


General notes:

在做类似的事情之前

grid[p1, --p2] = 1;

您应该始终检查您是否可能越界,例如喜欢

You should always check if your are maybe getting out of bounds e.g. like

private bool TryGoToPosition(int[,] grid, Vector2Int from, Vector2Int to)
{
    if(to.x >= 0 && to.x < grid.GetLength(0) - 1 && to.y >= 0 && to.y < grid.GetLength(1) - 1)
    {
        grid[from.x, from.y] = 0;
        grid[to.x, to.x] = 1;
    }
    else
    {
        Debug.LogWarning("Reached grid border! -> Ignored");
    }
}


然后我一般会简单地使用 Vector2Int 而不是将网格中的某个值设置为 01


Then I would simply work with a Vector2Int in general instead of setting some value in a grid to 0 or 1 like

Vector2Int gridDimensions = new Vector2Int(10, 16);
public ShipData currentShipData;
public ShipData JSON_ShipData;

private bool CanGoToPosition(Vector2Int to)
{
    return to.x >= 0 && to.x < gridDimensions.x - 1 && to.y >= 0 && to.y < gridDimensions.y - 1;
}

void Start()
{
    currentShipData.position = new Vector2Int(9, 0);

    panelhole.SetActive(false);
    panelturtle.SetActive(false);
    Debug.Log(JSON_ShipData.position);
    Debug.Log(shiposition.transform.position);
}

void Update()
{
    ......        

    if (Input.GetKeyDown(KeyCode.A))
    {
        if (CanGoToPosition(JSON_ShipData.position + Vector2Int.down))
        {
            currentShipData.position += Vector2Int.down;
        }
        else
        {
            Debug.Log("You can't move left!!");
        }
    }

    ...

    // Then after you handled user input for movement update the other data
    currentShipData.windspeed = windspeedData[JSON_ShipData.position.x, JSON_ShipData.position.y];
    currentShipData.flow = flowData[JSON_ShipData.position.x, JSON_ShipData.position.y];
    ...
}

然后按下按钮,您只需复制当前值

Then for the button press you simply only copy over the current values

public void button()
{
    JSON_ShipData.position = currentShipData.position;
    ...

    SaveintoJson();
}

这篇关于将二维数组保存为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆