LitJSON之JSON与对象间的相互映射

快速入门

JSON与对象间的相互映射

为了能在.NET程序中使用JSON格式的数据,我们首先能想到的方法是使用JSON文本去填充特定类别的新实例;或者用一种传统的方法去构建与输入的JSON文本相对应的数据结构,再或者用创建字典这种更为普遍的方法。
相反,一个简单的输出操作可能更加适合,使用对象中存储的数据来生成新的JSON字符串。
基于这种目的,litjson中包含了一个jsonmapper类,该类别为实现json到对象和对象到json转化提供了两种主要方法:JsonMapper.ToObject 和 JsonMapper.ToJson.

简单的JsonMapper 案例

如下列案例所示,ToObject 中有一个“JsonMapper.ToObject”的重载方法,可以用来指定返回的对象类型。

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的数据格式。

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

目录

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值