首页 > Web开发 > 详细

j.net 实现json的序列化与反序列化

时间:2017-10-21 23:48:04      阅读:283      评论:0      收藏:0      [点我收藏+]

首先理解,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 被多次重载,还提供其它很多功能的支持

j.net 实现json的序列化与反序列化

原文:http://www.cnblogs.com/ttkknetroad/p/7702740.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!