6

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.....

BatteryBackupUnit
  • 12,934
  • 1
  • 42
  • 68
abhishek
  • 63
  • 1
  • 1
  • 8
  • 1
    *how would i print content on screen after file parsing and how to write in file .do help.....*. What have you tried? – Mivaweb May 28 '15 at 09:20
  • Possible duplicate of [Serialize and Deserialize Json and Json Array in Unity](https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity) – Narottam Goyal Sep 25 '17 at 20:50

1 Answers1

4

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());
                }
Amit Kumar Ghosh
  • 3,618
  • 1
  • 20
  • 24