在unity中使用c#读取和解析Json文件

本文关键字:和解 Json 文件 读取 unity | 更新日期: 2023-09-27 17:51:05

代码

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
public class csharpfile:MonoBehaviour{
    public void LoadJson()
    {
        using (StreamReader r = new StreamReader("file.json"))
        {
            string json = r.ReadToEnd();
            List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);

        }
    }
    public class Item
    {
        public int millis;
        public string stamp;
        public DateTime datetime;
        public string light;
        public float temp;
        public float vcc;
    }
}

现在我想解析文件内容(file.json)

[ 
    { "millis": "1000", 
      "stamp": "1273010254", 
      "datetime": "2010/5/4 21:57:34", 
      "light": "333", 
      "temp": "78.32", 
      "vcc": "3.54" }, 
] 

文件解析后如何在屏幕上打印内容以及如何在文件中写入。do help.....

在unity中使用c#读取和解析Json文件

用于打印deserialized值:

                    string json = file.ReadToEnd();
                    List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
                    foreach (var item in items)
                    {
                        Console.WriteLine(item.millis);
                    }
编写/序列化:

                var serObj = JsonConvert.SerializeObject(new Item
                {
                    //assign values here
                });

                var stm = new MemoryStream();
                using (var sw = new StreamWriter(stm))
                {
                    var ser = new JsonSerializer();
                    ser.Serialize(sw, new Item());
                }