序列化对象:

----------------------------------------------------------

Person p = new Person()
{
Name = "Hexiang",
Birthday = DateTime.Parse("2017-02-20 14:30:00"),
Gender = "男",
Love = "Ball"
};
string strJson = JsonConvert.SerializeObject(p, Formatting.Indented);

------------------------------------------------------

序列化字典

Dictionary<string, int> dicPoints = new Dictionary<string, int>(){
{ "James", 9001 },
{ "Jo", 3474 },
{ "Jess", 11926 }
};

string strJson = JsonConvert.SerializeObject(dicPoints, Formatting.Indented);

------------------------------------

序列化list

List<string> lstGames = new List<string>()
{
"Starcraft",
"Halo",
"Legend of Zelda"
};

string strJson = JsonConvert.SerializeObject(lstGames);

-----------------------------------

序列化到json文件中

Person p = new Person()
{
Name = "Hexiang",
Birthday = DateTime.Parse("2017-02-20 14:30:00"),
Gender = "男",
Love = "Ball"
};
using (StreamWriter file = File.CreateText(@"d:\person.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, p);
}

--------------------------------

序列化 枚举

List<StringComparison> stringComparisons = new List<StringComparison>
{
StringComparison.CurrentCulture,
StringComparison.Ordinal
};

string jsonWithoutConverter = JsonConvert.SerializeObject(stringComparisons);

this.txtJson.Text = jsonWithoutConverter;//序列化出来是枚举所代表的整数值

string jsonWithConverter = JsonConvert.SerializeObject(stringComparisons, new StringEnumConverter());
this.txtJson.Text += "\r\n";
this.txtJson.Text += jsonWithConverter;//序列化出来是枚举所代表的文本值
// ["CurrentCulture","Ordinal"]

List<StringComparison> newStringComparsions = JsonConvert.DeserializeObject<List<StringComparison>>(
jsonWithConverter,
new StringEnumConverter());

-------------------------------------

序列化dataset

string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);

-------------------------------

序列化jrow

JavaScriptSettings settings = new JavaScriptSettings
{
OnLoadFunction = new JRaw("OnLoad"),
OnUnloadFunction = new JRaw("function(e) { alert(e); }")
};

string json = JsonConvert.SerializeObject(settings, Formatting.Indented);

-----------------------

反序列化list

string json = @"['Starcraft','Halo','Legend of Zelda']";
List<string> videogames = JsonConvert.DeserializeObject<List<string>>(json);
this.txtJson.Text = string.Join(", ", videogames.ToArray());

---------------------------------

反序列化字典

string json = @"{
'href': '/account/login.aspx',
'target': '_blank'
}";

Dictionary<string, string> dicAttributes = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

this.txtJson.Text = dicAttributes["href"];
this.txtJson.Text += "\r\n";
this.txtJson.Text += dicAttributes["target"];

--------------------------------

反序列化匿名类

var definition = new { Name = "" };

string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
this.txtJson.Text = customer1.Name;
this.txtJson.Text += "\r\n";

string json2 = @"{'Name':'Mike'}";
var customer2 = JsonConvert.DeserializeAnonymousType(json2, definition);
this.txtJson.Text += customer2.Name;

--------------------------------------------

反序列化dataset

string json = @"{
'Table1': [
{
'id': 0,
'item': 'item 0'
},
{
'id': 1,
'item': 'item 1'
}
]
}";

DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);

-----------------------------------------

从文件中反序列化对象

using (StreamReader file = File.OpenText(@"d:\person.json"))
{
JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(file, typeof(Person));
this.txtJson.Text = p.Name;
}

----------------------------------------------------

反序列化有构造函数的对象

string json = @"{'Url':'http://www.google.com'}";

//直接序列化会报错,需要设置JsonSerializerSettings中ConstructorHandling才可以。
Website website = JsonConvert.DeserializeObject<Website>(json, new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
});

this.txtJson.Text = website.Url;

------------------------------------------

反序列化对象,如果有构造函数中,创建对象,则用Json的进行替换

//
string json = @"{
'Name': 'James',
'Offices': [
'Auckland',
'Wellington',
'Christchurch'
]
}";

UserViewModel model1 = JsonConvert.DeserializeObject<UserViewModel>(json);

this.txtJson.Text = string.Join(",", model1.Offices);//默认会重复
this.txtJson.Text += "\r\n";

//每次从Json中创建新的对象
UserViewModel model2 = JsonConvert.DeserializeObject<UserViewModel>(json, new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace
});

this.txtJson.Text = string.Join(",", model2.Offices);

--------------------------------------

序列化对象的时候去掉没有赋值 的属性

Person person = new Person();

string jsonIncludeDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented);

this.txtJson.Text=(jsonIncludeDefaultValues);//默认的序列化,带不赋值的属性

this.txtJson.Text += "\r\n";

string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Ignore //去掉不赋值的属性
});

this.txtJson.Text+=(jsonIgnoreDefaultValues);

-----------------------------------------------------------------------

反序列化类中没有对应对属性 处理方法

string json = @"{
'FullName': 'Dan Deleted',
'Deleted': true,
'DeletedDate': '2013-01-20T00:00:00'
}";

try
{
JsonConvert.DeserializeObject<Account>(json, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error //要么忽略,要么报错
});
}
catch (JsonSerializationException ex)
{
this.txtJson.Text=(ex.Message);
// Could not find member 'DeletedDate' on object of type 'Account'. Path 'DeletedDate', line 4, position 23.
}

---------------------------------------------------------

去掉null值的序列化对象

Person person = new Person
{
Name = "Nigal Newborn"
};

//默认的序列化
string jsonIncludeNullValues = JsonConvert.SerializeObject(person, Formatting.Indented);

this.txtJson.Text=(jsonIncludeNullValues);
this.txtJson.Text += "\r\n";

//去掉Null值的序列化
string jsonIgnoreNullValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore //可以忽略,可以包含
});

this.txtJson.Text+=(jsonIgnoreNullValues);

-----------------------------

序列化的时候日期的格式化

DateTime mayanEndOfTheWorld = new DateTime(2012, 12, 21);

string jsonIsoDate = JsonConvert.SerializeObject(mayanEndOfTheWorld);

this.txtJson.Text = (jsonIsoDate);

this.txtJson.Text += "\r\n";
string jsonMsDate = JsonConvert.SerializeObject(mayanEndOfTheWorld, new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});

this.txtJson.Text += (jsonMsDate);
// "\/Date(1356044400000+0100)\/"
this.txtJson.Text += "\r\n";
string json = JsonConvert.SerializeObject(mayanEndOfTheWorld, new JsonSerializerSettings
{
DateFormatString = "yyyy-MM-dd",
Formatting = Formatting.Indented
});
this.txtJson.Text += json;

----------------------------

序列化设置时区

Flight flight = new Flight
{
Destination = "Dubai",
DepartureDate = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Unspecified),
DepartureDateUtc = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Utc),
DepartureDateLocal = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Local),
Duration = TimeSpan.FromHours(5.5)
};

string jsonWithRoundtripTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind
});

this.txtJson.Text=(jsonWithRoundtripTimeZone);
this.txtJson.Text += "\r\n";
string jsonWithLocalTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
});

this.txtJson.Text+=(jsonWithLocalTimeZone);
this.txtJson.Text += "\r\n";

string jsonWithUtcTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc
});

this.txtJson.Text += (jsonWithUtcTimeZone);
this.txtJson.Text += "\r\n";

string jsonWithUnspecifiedTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Unspecified
});

this.txtJson.Text += (jsonWithUnspecifiedTimeZone);

---------------------------------------

序列化默认设置

// settings will automatically be used by JsonConvert.SerializeObject/DeserializeObject
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};

Person s = new Person()
{
Name = "Eric",
Birthday = new DateTime(1980, 4, 20, 0, 0, 0, DateTimeKind.Utc),
Gender = "男",
Love = "Web Dude"
};

string json = JsonConvert.SerializeObject(s);
this.txtJson.Text = json;

-----------------------------------------

序列化ImmutableList

//ImmutableList<string> l = ImmutableList.CreateRange(new List<string>
// {
// "One",
// "II",
// "3"
// });

//string json = JsonConvert.SerializeObject(l, Formatting.Indented);

-------------------------------------------------

----------------------------------------

json 常用的序列化 反序列化对象 代码的更多相关文章

  1. php json与xml序列化/反序列化

    在web开发中对象的序列化与反序列化经常使用,比较主流的有json格式与xml格式的序列化与反序列化,今天想写个jsop的小demo,结果发现不会使用php序列化,查了一下资料,做个笔记 简单数组js ...

  2. Java序列化反序列化对象流ObjectInputStream、ObjectOutputStream

    使用Person类作为Object进行示范 注意:Object要能被写入流需要实现Serializable接口 存储的文件后缀名为.ser 示范Person类 import java.io.Seria ...

  3. 初尝Java序列化/反序列化对象

    看个类: package com.wjy.bytes; import java.io.Serializable; public class ObjTest implements Serializabl ...

  4. 用JSON.parse(JSON.stringify(itemData))序列化反序列化实现‘深度复制’

    还可以用来去除值不具有JSON 表示形式(数字.字符串.逻辑值.数组.对象.null)的属性,也就是说像undefined和function这样的属性值.

  5. JSR310-LocalDateTime序列化 & 反序列化

    问题 springboot 版本:spring-boot 2.3.12 今天在开发一个redis 热key服务端的过程中,碰到2个问题: jdk8的LocalDateTime,LocalDate,Lo ...

  6. JSON解析与序列化

    JSON之所以流行,拥有与JavaScript类似的语法并不是全部原因.更重要的一个原因是,可以把JSON数据结构解析为有用的 JavaScript对象.与XML数据结构要解析成DOM文档而且从中提取 ...

  7. .NET中如何使用反序列化JSON字符串/序列化泛型对象toJsonStr

    在进行 .NET Web MVC 框架开发的网站程序的时候,我们都会遇到最关键的问题,数据传输.   .NET MVC 4中的ControllerBase类建议我们用ViewBag动态数据字典形式(t ...

  8. JSON和XML格式与对象的序列化及反序列化的辅助类

    下面的代码主要是把对象序列化为JSON格式或XML格式等 using System; using System.Collections.Generic; using System.Globalizat ...

  9. python常用模块(模块和包的解释,time模块,sys模块,random模块,os模块,json和pickle序列化模块)

    1.1模块 什么是模块: 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文 ...

随机推荐

  1. Even Odds (java)

    从1到n的奇数,从1到n之间的偶数,排列在一起,找到第k个数 Input 输入包含 n and k (1 ≤ k ≤ n ≤ 1012). Please, do not use the %lld sp ...

  2. 常用模块(json/pickle/shelve/XML)

    一.json模块(重点) 一种跨平台的数据格式 也属于序列化的一种方式 介绍模块之前,三个问题: 序列化是什么? 我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化. 反序列化又是什么? 将 ...

  3. 2017-2018-2 20165306 实验三《敏捷开发与XP实践》实验报告

    实验三<敏捷开发与XP实践>实验报告 实验报告封面 实验内容 XP基础 XP核心实践 相关工具 实验步骤 (一) 敏捷开发与XP实践-1 实验要求: 参考 代码规范 安装alibaba 插 ...

  4. 爬虫系列之BeautifulSoup

    BeautifulSoup是处理爬虫的一个强大工具,在HTML页面中,是由各种标签构成的,BeautifulSoup的功能就是从标签下手的,它是解析.遍历.维护“标签树”的功能库. Beautiful ...

  5. HDU 1247 Hat’s Words(字典树)

    http://acm.hdu.edu.cn/showproblem.php?pid=1247 题意: 给出一些单词,问哪些单词可以正好由其他的两个单词首尾相连而成. 思路: 先将所有单独插入字典树,然 ...

  6. Windows下使用命令安装Python的scipy库出错的解决

    平时使用Python都是在Sublime下使用,不想使用IDE.使用各种库时安装也就是使用pip安装即可.来说说今天自己遇到的一个问题:使用scipy数学库时,使用命令: pip install sc ...

  7. Centos7 linux下通过源码安装redis以及使用

    下载redis安装包 wget http://download.redis.io/releases/redis-5.0.3.tar.gz 解压压缩包 tar -zxvf redis-.tar.gz y ...

  8. centos7 彻底卸载PHP7

    [root@xxx php-memcached]# rpm -qa | grep php php70w-common--.w7.x86_64 php70w-devel--.w7.x86_64 php7 ...

  9. Mysql简单入门

    这两天比较懒,没有学习,这个是我问一个学java的小伙伴要的sql的总结资料,大体语句全在上面了,复制到博客上,以后忘记可以查看 #1命令行连接MySQLmsyql -u root -proot;#2 ...

  10. char,String,int类型互转

    1.ascci码对应转换 字符,对应的ascii(其实是UTF-16)码:     char c='a'; int k=(int) c;    结果k=97 数字,对应的字符:     int k=9 ...