Litjson快速入门

LitJSON是一个C#.Net库,用于处理JSON字符串的转换。JsonMapper类提供了ToObject和ToJson方法进行JSON-to-object和object-to-JSON的转换。此外,JsonReader和JsonWriter接口允许按流方式读写JSON数据,而配置库的行为可以调整以适应不同的需求。
摘要由CSDN通过智能技术生成

介绍

Json是一个简单但功能强大的,用于specify data。它定义了简单的数值类型例如布尔型、数字(整型和实数)和字符串,以及一些数据结构:数组(list)和对象(字典)。LitJSON是一个C#.Net库,用于处理JSON(JavaScript Object Notation)字符串的转换。

将JSON映射到Object及反映射

为了在.Net程序中使用JSON格式的数据,最先在心中想到的方法是在一个特定类的实例中填充JSON文本,或者一个定制的类,用于匹配输入的JSON文本结构,也可以更通用的使用一个类似字典的类。

相反,为了将存储在对象中的数据构建新的JSON字符串,如果有一个简单导出的操作就很棒了。

为了达到这一点,LitJSON包含JsonMapper类,可以提供两个主要方法来达到JSON-to-object和object-to-JSON的转换。这两个方法是JsonMapper.ToObject和JsonMapper.ToJson。

简单的JsonMapper示例

using LitJson;
using System;

public class Person
{
    // C# 3.0 auto-implemented properties
    public string   Name     { get; set; }
    public int      Age      { get; set; }
    public DateTime Birthday { get; set; }
}

public class JsonSample
{
    public static void Main()
    {
        PersonToJson();
        JsonToPerson();
    }

    public static void PersonToJson()
    {
        Person bill = new Person();

        bill.Name = "William Shakespeare";
        bill.Age  = 51;
        bill.Birthday = new DateTime(1564, 4, 26);

        string json_bill = JsonMapper.ToJson(bill);

        Console.WriteLine(json_bill);
    }

    public static void JsonToPerson()
    {
        string json = @"
            {
                ""Name""     : ""Thomas More"",
                ""Age""      : 57,
                ""Birthday"" : ""02/07/1478 00:00:00""
            }";

        Person thomas = JsonMapper.ToObject<Person>(json);

        Console.WriteLine("Thomas' age: {0}", thomas.Age);
    }
}

输出示例:

{"Name":"William Shakespeare","Age":51,"Birthday":"04/26/1564 00:00:00"}
Thomas' age: 57

JsonMapper.ToObject的非泛型变体使用

当要读取JSON数据时,匹配特定数据结构的类不可用或不需要的时候,使用者可以使用ToObject的非泛型变体,可以返回一个JsonData实例。JsonData是一个可以保存任何JSON支持的数据类型的普通类,包括list和字典。

using LitJson;
using System;

public class JsonSample
{
    public static void Main()
    {
        string json = @"
          {
            ""album"" : {
              ""name""   : ""The Dark Side of the Moon"",
              ""artist"" : ""Pink Floyd"",
              ""year""   : 1973,
              ""tracks"" : [
                ""Speak To Me"",
                ""Breathe"",
                ""On The Run""
              ]
            }
          }
        ";

        LoadAlbumData(json);
    }

    public static void LoadAlbumData(string json_text)
    {
        Console.WriteLine("Reading data from the following JSON string: {0}",
                          json_text);

        JsonData data = JsonMapper.ToObject(json_text);

        // Dictionaries are accessed like a hash-table
        Console.WriteLine("Album's name: {0}", data["album"]["name"]);

        // Scalar elements stored in a JsonData instance can be cast to
        // their natural types
        string artist = (string) data["album"]["artist"];
        int    year   = (int) data["album"]["year"];

        Console.WriteLine("Recorded by {0} in {1}", artist, year);

        // Arrays are accessed like regular lists as well
        Console.WriteLine("First track: {0}", data["album"]["tracks"][0]);
    }
}

输出示例:

Reading data from the following JSON string:
          {
            "album" : {
              "name"   : "The Dark Side of the Moon",
              "artist" : "Pink Floyd",
              "year"   : 1973,
              "tracks" : [
                "Speak To Me",
                "Breathe",
                "On The Run"
              ]
            }
          }

Album's name: The Dark Side of the Moon
Recorded by Pink Floyd in 1973
First track: Speak To Me

Reader和Writer

一些开发人员对通过类来让JSON数据可以通过类似流的方式读取和写入数据。这在LitJSON中有可供选择的接口,它们是JsonReader和JsonWriter。

它们实际是是这个库的基础,JsonMapper是以它们为基础构建的。所以在某种程度上,开发人员可以将reader和writer类视为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

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是一种非常简洁的数据交换格式,功能不多不少。出于这个原因,在程序中使用JSON处理数据时,可能需要慎重考虑一些超出JSON规范范围的小细节。

例如,JSON字符串使用单引号分隔字符串,或者将JS风格注释作为文档的一种格式。这些东西不属于JSON标准,但是通常一些开发人员这么使用,因此可能有时我们想要根据情况放宽或者严格标准。再或者,如果想把一个.net对象转换成JSON字符串如何打印的更漂亮。

这些可以通过修改更改JsonReader和JsonWriter的一些属性来实现。

JsonReader配置

using LitJson;
using System;

public class JsonReaderConfigExample
{
    public static void Main()
    {
        string json;

        json = " /* these are some numbers */ [ 2, 3, 5, 7, 11 ] ";
        TestReadingArray(json);

        json = " [ \"hello\", 'world' ] ";
        TestReadingArray(json);
    }

    static void TestReadingArray(string json_array)
    {
        JsonReader defaultReader, customReader;

        defaultReader = new JsonReader(json_array);
        customReader  = new JsonReader(json_array);

        customReader.AllowComments            = false;
        customReader.AllowSingleQuotedStrings = false;

        ReadArray(defaultReader);
        ReadArray(customReader);
    }

    static void ReadArray(JsonReader reader)
    {
        Console.WriteLine("Reading an array");

        try {
            JsonData data = JsonMapper.ToObject(reader);

            foreach (JsonData elem in data)
                Console.Write("  {0}", elem);

            Console.WriteLine("  [end]");
        }
        catch (Exception e) {
            Console.WriteLine("  Exception caught: {0}", e.Message);
        }
    }
}

输出示例:

eading an array
  2  3  5  7  11  [end]
Reading an array
  Exception caught: Invalid character '/' in input string
Reading an array
  hello  world  [end]
Reading an array
  Exception caught: Invalid character ''' in input string

JsonWriter配置

using LitJson;
using System;

public enum AnimalType
{
    Dog,
    Cat,
    Parrot
}

public class Animal
{
    public string     Name { get; set; }
    public AnimalType Type { get; set; }
    public int        Age  { get; set; }
    public string[]   Toys { get; set; }
}

public class JsonWriterConfigExample
{
    public static void Main()
    {
        var dog = new Animal {
            Name = "Noam Chompsky",
            Type = AnimalType.Dog,
            Age  = 3,
            Toys = new string[] { "rubber bone", "tennis ball" }
        };

        var cat = new Animal {
            Name = "Colonel Meow",
            Type = AnimalType.Cat,
            Age  = 5,
            Toys = new string[] { "cardboard box" }
        };

        TestWritingAnimal(dog);
        TestWritingAnimal(cat, 2);
    }

    static void TestWritingAnimal(Animal pet, int indentLevel = 0)
    {
        Console.WriteLine("\nConverting {0}'s data into JSON..", pet.Name);
        JsonWriter writer1 = new JsonWriter(Console.Out);
        JsonWriter writer2 = new JsonWriter(Console.Out);

        writer2.PrettyPrint = true;
        if (indentLevel != 0)
            writer2.IndentValue = indentLevel;

        Console.WriteLine("Default JSON string:");
        JsonMapper.ToJson(pet, writer1);

        Console.Write("\nPretty-printed:");
        JsonMapper.ToJson(pet, writer2);
        Console.WriteLine("");
    }
}

输出示例:

Converting Noam Chompsky's data into JSON..
Default JSON string:
{"Name":"Noam Chompsky","Type":0,"Age":3,"Toys":["rubber bone","tennis ball"]}
Pretty-printed:
{
    "Name" : "Noam Chompsky",
    "Type" : 0,
    "Age"  : 3,
    "Toys" : [
        "rubber bone",
        "tennis ball"
    ]
}

Converting Colonel Meow's data into JSON..
Default JSON string:
{"Name":"Colonel Meow","Type":1,"Age":5,"Toys":["cardboard box"]}
Pretty-printed:
{
  "Name" : "Colonel Meow",
  "Type" : 1,
  "Age"  : 5,
  "Toys" : [
    "cardboard box"
  ]
}

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值