跳至正文

Unity读取和解析JSON文件(3)-JsonReader和JsonWriter

  • Unity
  • Unity版本:2018.4.17

JsonMapper的底层是JsonReader和JsonWriter,这两个类也是LitJson库的基础,它们提供了流式方式读写JSON数据的接口。

使用JsonReader

通过JsonReader可以得到JSON数据的所有信息,包括字段名、字段类型,字段值等。

using LitJson;
using System;

public class DataReader
{
    public static void Main()
    {
        string sample = @"{
            ""name""  : ""Bill"",
            ""age""   : 32,
            ""awake"" : true,
            ""n""     : 1994.0226,
            ""note""  : [ ""life"", ""is"", ""but"", ""a"", ""dream"" ]
          }";

        PrintJson(sample);
    }

    public static void PrintJson(string json)
    {
        JsonReader reader = new JsonReader(json);

        Console.WriteLine ("{0,14} {1,10} {2,16}", "Token", "Value", "Type");
        Console.WriteLine (new String ('-', 42));

        // The Read() method returns false when there's nothing else to read
        while (reader.Read()) {
            string type = reader.Value != null ?
                reader.Value.GetType().ToString() : "";

            Console.WriteLine("{0,14} {1,10} {2,16}",
                              reader.Token, reader.Value, type);
        }
    }
}

输出如下

Token         Value             Type
------------------------------------------
ObjectStart                            
PropertyName  name              System.String
String        Bill              System.String
PropertyName  age               System.String
  Int         32                System.Int32
PropertyName  awake             System.String
Boolean       True              System.Boolean
PropertyName  n                 System.String
Double        1994.0226         System.Double
PropertyName  note              System.String
ArrayStart                            
String        life              System.String
String        is                System.String
String        but               System.String
String        a                 System.String
String        dream             System.String
ArrayEnd                            
ObjectEnd

使用JsonWriter

JsonWriter类非常简单,请记住,如果要将某个任意对象转换为JSON字符串,通常只需使用JsonMapper.ToJson

using LitJson;
using System;
using System.Text;

public class DataWriter
{
    public static void Main()
    {
        StringBuilder sb = new StringBuilder();
        JsonWriter writer = new JsonWriter(sb);

        writer.WriteArrayStart();
        writer.Write(1);
        writer.Write(2);
        writer.Write(3);

        writer.WriteObjectStart();
        writer.WritePropertyName("color");
        writer.Write("blue");
        writer.WriteObjectEnd();

        writer.WriteArrayEnd();

        Console.WriteLine(sb.ToString());
    }
}

输出如下

[1,2,3,{"color":"blue"}]
标签:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注