Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and parse a Json File in C# in unity

Tags:

json

c#

unity3d

Here is the code

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;
    }
}

Now i want to parse the file content (file.json)

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

how would i print content on screen after file parsing and how to write in file .do help.....

like image 719
abhishek Avatar asked Sep 27 '22 19:09

abhishek


1 Answers

for printing the deserialized value:

                    string json = file.ReadToEnd();
                    List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
                    foreach (var item in items)
                    {
                        Console.WriteLine(item.millis);
                    }

for writing/serializing:

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

Or

                var stm = new MemoryStream();
                using (var sw = new StreamWriter(stm))
                {
                    var ser = new JsonSerializer();
                    ser.Serialize(sw, new Item());
                }
like image 126
Amit Kumar Ghosh Avatar answered Nov 05 '22 19:11

Amit Kumar Ghosh