LitJSON之JSON读取和写入

  • JSON读取和写入
    • 使用JsonReader例子
    • 使用JsonWriter
    • 目录

JSON读取和写入

一些开发者可能熟悉JSON数据的另一种处理方法:即通过利用类似流的方式来读取和写入数据。实现这种方法的是JsonReader类和 JsonWriter类。

这两个类实际上是整个库的基础。JsonMapper 建立在这两个类型之上。开发者可以认为读取和写入类是Litjson的底层程序接口。

使用JsonReader例子

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"}]

目录

  • 介绍
  • 快速开始
    • 将JSON与Object相互映射
    • JSON的读取和写入
    • 配置库

你可能感兴趣的:(LitJSON)