zoukankan      html  css  js  c++  java
  • j.net 实现json的序列化与反序列化

    首先理解,json是一种数据格式,而非一种数据类型。json格式的数据类型在c#中为string

    开始测试:

    使用Newtonsoft.Json包

    一:json转object

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace JsonTest
    {
        class Program
        {
            static void Main(string[] args)
            {
    //构造json字符串
    var json = "{ 'people':" + "[{ 'firstName': 'Brett', 'lastName':'McLaughlin', 'email': 'aaaa' }," + "{ 'firstName': 'Jason', 'lastName':'Hunter', 'email': 'bbbb'}," + "{ 'firstName': 'Elliotte', 'lastName':'Harold', 'email': 'cccc' }]}";
    //使用Newtonsoft.Json中的JsonConvert转换json
    var jsonObj = JsonConvert.DeserializeObject<PeopleFather>(json); foreach (People item in jsonObj.people) { Console.WriteLine("firstName:"+item.firstName); Console.WriteLine("lastName:" + item.lastName); Console.WriteLine("email:" + item.email); Console.WriteLine("------"); } Console.ReadLine(); } } //构造json要转换的类 public class PeopleFather { public List<People> people { get; set; } } public class People { public string firstName { get; set; } public string lastName { get; set; } public string email { get; set; } } }

    结果:

     二:对象类型转json

    同样使用Newtonsoft.Json包

     static void Main(string[] agrs)
            {       
                var people = new People();
                people.firstName = "a";
                people.lastName = "b";
                people.email = "c";
                var json = JsonConvert.SerializeObject(people);
                Console.WriteLine(json);
                Console.ReadLine();
            }
    
     public class People {
            public string firstName { get; set; }
            public string lastName { get; set; }
            public string email { get; set; }
        }

    需要说明的是

    JsonConvert.SerializeObjectzai 被多次重载,还提供其它很多功能的支持
  • 相关阅读:
    使用java.util.Properties类读写配置文件
    maven配置文件setting.xml字段注释
    使用Nexus搭建Maven代理仓库
    Memcached 内存管理详解
    Memcached常用命令及使用说明
    使用NTP协议服务器时间同步
    Eclipse打JAR包的使用
    Eclipse插件的各种安装方法
    Java中代理对象的使用小结
    tp5框架成功、失败提示模板修改
  • 原文地址:https://www.cnblogs.com/ttkknetroad/p/7702740.html
Copyright © 2011-2022 走看看