想了解Newtonsoft.Json解析json数据的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于如何解析json数据的相关问题,此外,我们还将为您介绍关于.net使用Newtonsoft
想了解Newtonsoft.Json解析json数据的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于如何解析json数据的相关问题,此外,我们还将为您介绍关于.net 使用 Newtonsoft.Json 输出树状 json字符串、.Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程、Android-Gson解析JSON数据(JSON对象/JSON数组)、C# dynamic类型序列化和反序列化之Newtonsoft.Json,动态解析远端返回的jSON数据的新知识。
本文目录一览:- Newtonsoft.Json解析json数据(如何解析json数据)
- .net 使用 Newtonsoft.Json 输出树状 json字符串
- .Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程
- Android-Gson解析JSON数据(JSON对象/JSON数组)
- C# dynamic类型序列化和反序列化之Newtonsoft.Json,动态解析远端返回的jSON数据
Newtonsoft.Json解析json数据(如何解析json数据)
namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); string JsonData="{'result':'200','info':[{'_cid':5,'_name':'Iphone4','_parentid':2,'_status':true},{'_cid':7,'_name':'手机外套',{'_cid':8,'_name':'手机模','_status':true}]}"; WindowsFormsApplication2.BackInfo backinfo = (WindowsFormsApplication2.BackInfo) JsonConvert.DeserializeObject(JsonData,typeof(WindowsFormsApplication2.BackInfo)); if (backinfo.result == "200")//成功 { List<WindowsFormsApplication2.IphoneClassify> list = backinfo.info; Dictionary<int,String> dic = new System.Collections.Generic.Dictionary<int,String>(); for (int i = 0; i < list.Count; i++) { WindowsFormsApplication2.IphoneClassify classify = (WindowsFormsApplication2.IphoneClassify)list[i]; dic.Add(classify._cid,classify._name); } //this.DataList1.DataSource = dic; //this.DataList1.DataBind(); } else { //失败 } } } /// <summary> ///返回JSON属性 /// </summary> [Serializable] public class BackInfo { public BackInfo() { } public String result { get; set; } public List<IphoneClassify> info { get; set; } } /// <summary> ///产品类型 /// </summary> [Serializable] public class IphoneClassify { public int _cid { get; set; } public string _name { get; set; } public int _parentid { get; set; } public bool _status { get; set; } } }
.net 使用 Newtonsoft.Json 输出树状 json字符串
测试环境:.net FrameWork 4.0
操作系统:window Server 2008 R2
Newtonsoft.Json 下载地址:http://json.codeplex.com/
1、解压缩下载文件夹:Json50r8
2、引入Json50r8/Bin 下的 相对应.net版本的dll文件 到项目中
执行以下代码:
using System; using System.Collections.Generic; using Newtonsoft.Json; public partial class _Default : System.Web.UI.Page { private string jsonString = @"[ { 'id': '1','text': '电脑整机','parentid': '0','children': [ { 'id': '2','text': '笔记本','parentid': '1','children': [ { 'id': '31','text': 'SONY','parentid': '2','children': [] },{ 'id': '23','text': 'LENOVO',{ 'id': '25','text': 'IBM',{ 'id': '26','text': '宏基',{ 'id': '27','text': '联想',{ 'id': '28','text': '联想2','children': [] } ] },{ 'id': '3','text': '上网本',{ 'id': '4','text': '平板电脑',{ 'id': '5','text': '台式机',{ 'id': '6','text': '服务器','children': [] } ] },{ 'id': '7','text': '电脑配件','children': [ { 'id': '8','text': 'cpu','parentid': '7',{ 'id': '9','text': '主板',{ 'id': '10','text': '显卡',{ 'id': '11','text': '硬盘',{ 'id': '12','text': '内存',{ 'id': '13','text': '机箱',{ 'id': '14','text': '电源',{ 'id': '15','text': '显示器',{ 'id': '16','text': '刻录机/光驱',{ 'id': '17','text': '声卡',{ 'id': '18','text': '扩展卡','children': [] } ] },{ 'id': '32','text': '手机','children': [ { 'id': '33','text': '诺基亚','parentid': '32','children': [ { 'id': '34','text': '华为','children': [] } ] },{ 'id': '34','text': '三星','text': '小米','text': '苹果','children': [] } ] },'text': '篮球','parentId': '1','children': [] } ];"; protected void Page_Load(object sender,EventArgs e) { treeNode rootNode = new treeNode(); rootNode.id="1"; rootNode.text="电脑整机"; rootNode.parentid="0"; treeNode childNode1 = new treeNode(); childNode1.id="2"; childNode1.text="笔记本"; childNode1.parentid="1"; treeNode childNode2 = new treeNode(); childNode2.id="3"; childNode2.text="SONY"; childNode2.parentid="1"; if (rootNode.children == null) rootNode.children = new List<treeNode>(); rootNode.children.Add(childNode1); rootNode.children.Add(childNode2); string json = JsonConvert.SerializeObject(rootNode,Formatting.Indented); } /// <summary> /// 树结构(根据js插件定义的数据结构) /// </summary> public class treeNode { private string _id; private string _text; private string _parentid; private List<treeNode> _children; public string id { get { return _id; } set { _id = value; } } public string text { get { return _text; } set { _text = value; } } public string parentid { get { return _parentid; } set { _parentid = value; } } public List<treeNode> children { get { return _children; } set { _children = value; } } } }
.Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程
JSON作为一种轻量级的数据交换格式,简单灵活,被很多系统用来数据交互,作为一名.NET开发人员,JSON.NET无疑是最好的序列化框架,支持XML和JSON序列化,高性能,免费开源,支持LINQ查询。目前已被微软集成于webapi框架之中,因此,熟练掌握JSON.NET相当重要,这篇文章是零度参考官网整理的示例,通过这些示例,可以全面了解JSON.NET提供的功能。
Newtonsoft.Json的地址:
官网:http://json.codeplex.com/
源码地址:https://github.com/JamesNK/Newtonsoft.Json
Newtonsoft.Json.dll下载:https://github.com/JamesNK/Newtonsoft.Json/releases
1、使用Newtonsoft.Json(JSON.NET)序列化对象,通过Newtonsoft.Json.Formatting将json格式化输出。
Account account = new Account { Email = "1930906722@qq.com",Active = true,CreatedDate =DateTime.Now,Roles = new List<string> { "User","Admin" } }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(account,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
public class Account { public string Name { get; set; } public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
执行结果:
2、使用Newtonsoft.Json(JSON.NET)序列化List集合:
List<string> videogames = new List<string> { "HTML5","JavaScript",".net","c#",".net core" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(videogames); Console.WriteLine(json);
执行结果:
3、使用Newtonsoft.Json(JSON.NET)序列化dictionary字典
System.Collections.Generic.Dictionary<string,string> dic = new System.Collections.Generic.Dictionary<string,string> { { "Name","张三" },{ "Age","20" },{ "Email","193090622@qq.com" } }; string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(dic,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json1); Console.WriteLine(""); Console.WriteLine("未格式化的json:"); string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(dic,Newtonsoft.Json.Formatting.None); Console.WriteLine(json2);
执行结果:
4、Newtonsoft.Json(JSON.NET)将序列化结果保存到指定的文件:
User movie = new User { Name = "张三",Age = 1993 }; using (System.IO.StreamWriter file = System.IO.File.CreateText(@"F:\UserInfo.txt")) { Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); serializer.Serialize(file,movie); }
public class User { public string Name { set; get; } public int Age { set; get; } }
执行后保存到文件的结果:
5、Newtonsoft.Json(JSON.NET)基于枚举类型的JsonConverters转换器
List<JosnEnum> list = new List<JosnEnum> { JosnEnum.NotStartus,JosnEnum.Startus }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(list); Console.WriteLine(json); Console.WriteLine(""); System.Collections.Generic.Dictionary<string,int> dic = new System.Collections.Generic.Dictionary<string,int> { {((JosnEnum)(int)JosnEnum.NotStartus).ToString(),(int)JosnEnum.NotStartus},{((JosnEnum)(int)JosnEnum.Startus).ToString(),(int)JosnEnum.Startus} }; string dicJson = Newtonsoft.Json.JsonConvert.SerializeObject(dic); Console.WriteLine(dicJson); Console.WriteLine(""); List<JosnEnum> list2 = new List<JosnEnum> { JosnEnum.NotStartus,JosnEnum.Startus }; string json3 = Newtonsoft.Json.JsonConvert.SerializeObject(list2,new Newtonsoft.Json.Converters.StringEnumConverter()); Console.WriteLine(json3); Console.WriteLine(""); List<JosnEnum> result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<JosnEnum>>(json3,new Newtonsoft.Json.Converters.StringEnumConverter()); Console.WriteLine(string.Join(",",result.Select(c => c.ToString())));
public enum JosnEnum { NotStartus = 0,Startus = 1 }
执行结果:
6、Newtonsoft.Json(JSON.NET)通过JRaw将JS函数序列化到JSON中
JavaScriptSettings settings = new JavaScriptSettings { OnLoadFunction = new Newtonsoft.Json.Linq.JRaw("OnLoad"),OnSucceedFunction = new Newtonsoft.Json.Linq.JRaw("function(e) { alert(e); }") }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(settings,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
public class JavaScriptSettings { public Newtonsoft.Json.Linq.JRaw OnLoadFunction { get; set; } public Newtonsoft.Json.Linq.JRaw OnSucceedFunction { get; set; } }
7、使用Newtonsoft.Json(JSON.NET)将json反序列化对象
string json = @"{ 'Email': '1930906722@qq.com','Active': true,'CreatedDate': '2016-11-26 20:39','Roles': [ 'User','Admin' ] }"; Account account = Newtonsoft.Json.JsonConvert.DeserializeObject<Account>(json); Console.WriteLine(account.Email);
public class Account { public string Name { get; set; } public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
执行结果:
8、使用Newtonsoft.Json(JSON.NET)反序列化List集合:
string json = @"['Html5','C#','.Net','.Net Core']"; List<string> videogames = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(json); Console.WriteLine(string.Join(",videogames));
执行结果:
9、使用Newtonsoft.Json(JSON.NET)反序列化dictionary字典
string json = @"{'Name': '张三','Age': '23'}"; var htmlAttributes = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>>(json); Console.WriteLine(htmlAttributes["Name"]); Console.WriteLine(htmlAttributes["Age"]);
执行结果:
10、使用Newtonsoft.Json(JSON.NET)序列化var匿名类型,有时候,我们并不需要先定义一个类,然后new一个对象后再进行序列化,JSON.NET支持匿名类型的序列化和反序列化。
var test1 = new { Name = "李四",Age = 26 }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(test1); Console.WriteLine(json); Console.WriteLine(""); var test2 = new { Name = "",Age = 0 }; string json1 = @"{'Name':'张三','Age':'25'}"; var result = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(json1,test2); Console.WriteLine(result.Name);
执行结果:
11、Newtonsoft.Json(JSON.NET)用新JSON字符串填充指定对象的属性值
Account account = new Account { Email = "1930906722@qq.com",CreatedDate = DateTime.Now,"Admin" } }; string json = @"{'Active': false,'Roles': ['Expired']}"; Newtonsoft.Json.JsonConvert.PopulateObject(json,account); Console.WriteLine(account.Active); Console.WriteLine(account.Email);
public class Account { public string Name { get; set; } public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
执行结果:
12、使用Newtonsoft.Json(JSON.NET)反序列化时可指定构造函数:
首先我们定义如下的类型,我们希望JSON.NET反序列化对象时使用第2个构造函数,我们将第一个默认构造函数屏蔽,标记为私有private修饰符。第2个构造函数需要指定一个website对象作为参数,如果提供的参数为null则抛出异常:
public class Website { public string Url { get; set; } private Website() { } public Website(Website website) { if (website == null) throw new ArgumentNullException("website"); Url = website.Url; } }
现在使用一般的方式反序列化一个JSON字符串。执行出现的结果:
我们发现该序列化方法抛出了异常,并没有按照我们预想的方式进行反序列化,JSON.NET提供如下的方式指定公有构造函数。
string json = @"{'Url':'http://www.cnblogs.com/linJie1930906722/'}"; Website website = Newtonsoft.Json.JsonConvert.DeserializeObject<Website>(json,new Newtonsoft.Json.JsonSerializerSettings { ConstructorHandling = Newtonsoft.Json.ConstructorHandling.AllowNonPublicDefaultConstructor }); Console.WriteLine(website.Url);
执行结果:
另外,JSON.NET提供了指定任何构造函数的JsonConstructorAttribute特性,只需要在构造函数上标记,即可指定构造函数。
public class Users { public string UserName { get; private set; } public bool Enabled { get; private set; } public Users() { } [Newtonsoft.Json.JsonConstructor] public Users(string userName,bool enabled) { UserName = userName; Enabled = enabled; } }
string json = @"{""UserName"": ""希特勒"",""Enabled"": true}"; Users user = Newtonsoft.Json.JsonConvert.DeserializeObject<Users>(json); Console.WriteLine(user.UserName);
执行结果:
13、当对象的属性为默认值(0或null)时不序列化该属性
public class Person { public string Name { get; set; } public int Age { get; set; } public Person Partner { get; set; } public decimal? Salary { get; set; } }
Person person1 = new Person(); string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(person1,Newtonsoft.Json.Formatting.Indented,new Newtonsoft.Json.JsonSerializerSettings { DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore }); Console.WriteLine(json1); Console.WriteLine(""); Person person2 = new Person(){Name = "奥巴马"}; string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(person2,new Newtonsoft.Json.JsonSerializerSettings { DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore }); Console.WriteLine(json2);
执行结果:
14、Newtonsoft.Json(JSON.NET)中忽略null值得处理器
public class Person { public string Name { get; set; } public int Age { get; set; } public Person Partner { get; set; } public decimal? Salary { get; set; } }
Person person = new Person { Name = "张三",Age = 46 }; string jsonIncludeNullValues = Newtonsoft.Json.JsonConvert.SerializeObject(person,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(jsonIncludeNullValues); Console.WriteLine(""); string json = Newtonsoft.Json.JsonConvert.SerializeObject(person,new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }); Console.WriteLine(json);
执行结果:
15、JSON.NET中循环引用的处理方法
Employee employee1 = new Employee { Name = "张三" }; Employee employee2 = new Employee { Name = "李四" }; employee1.Manager = employee2; employee2.Manager = employee2; string json = Newtonsoft.Json.JsonConvert.SerializeObject(employee1,new Newtonsoft.Json.JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore }); Console.WriteLine(json);
public class Employee { public string Name { get; set; } public Employee Manager { get; set; } }
执行结果:
16、通过ContractResolver指定属性名首字母小写,通常,在.NET中属性采用PascalCase规则(首字母大写),在JavaScript中属性名使用CamelCase规则(首字母小写),我们希望序列化后的JSON字符串符合CamelCase规则,JSON.NET提供的ContractResolver可以设置属性名小写序列化
public class User { public string Name { set; get; } public int Age { set; get; } }
User person = new User { Name = "张三",Age =52 }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(person,new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }); Console.WriteLine(json);
执行结果:
17、JSON.NET中通过特性序列化枚举类型
public enum ProductStatus { NotConfirmed,Active,Deleted } public class Product { public string Name { get; set; } [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public ProductStatus Status { get; set; } }
Product user = new Product { Name = @"羽绒服",Status = ProductStatus.Deleted }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(user,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
18、指定需要序列化的属性
[Newtonsoft.Json.JsonObject(Newtonsoft.Json.MemberSerialization.OptIn)] public class Categroy { //Id不需要序列化 public Guid Id { get; set; } [Newtonsoft.Json.JsonProperty] public string Name { get; set; } [Newtonsoft.Json.JsonProperty] public int Size { get; set; } }
Categroy categroy = new Categroy { Id = Guid.NewGuid(),Name = "内衣",Size = 52 }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(categroy,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
19、序列化对象时指定属性名
public class Videogame { [Newtonsoft.Json.JsonProperty("name")] public string Name { get; set; } [Newtonsoft.Json.JsonProperty("release_date")] public DateTime ReleaseDate { get; set; } }
Videogame starcraft = new Videogame { Name = "英雄联盟",ReleaseDate = DateTime.Now }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(starcraft,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
20、序列化时指定属性在JSON中的顺序
public class Personl { [Newtonsoft.Json.JsonProperty(Order = 2)] public string FirstName { get; set; } [Newtonsoft.Json.JsonProperty(Order = 1)] public string LastName { get; set; } }
Personl person = new Personl { FirstName = "张三",LastName = "李四" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(person,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
21、反序列化指定属性是否必须有值必须不为null,在反序列化一个JSON时,可通过JsonProperty特性的required指定反序列化行为,当反序列化行为与指定的行为不匹配时,JSON.NET将抛出异常,required是枚举,required.Always表示属性必须有值切不能为null,required.AllowNull表示属性必须有值,但允许为null值。
public class Order { [Newtonsoft.Json.JsonProperty(required = Newtonsoft.Json.required.Always)] public string Name { get; set; } [Newtonsoft.Json.JsonProperty(required = Newtonsoft.Json.required.AllowNull)] public DateTime? ReleaseDate { get; set; } }
string json = @"{ 'Name': '促销订单','ReleaseDate': null }"; Order order = Newtonsoft.Json.JsonConvert.DeserializeObject<Order>(json); Console.WriteLine(order.Name); Console.WriteLine(order.ReleaseDate);
执行结果:
22、通过特性指定null值忽略序列化
public class Vessel { public string Name { get; set; } [Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public DateTime? launchdate { get; set; } }
Vessel vessel = new Vessel { Name = "张三" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(vessel,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
23、忽略不需要序列化的属性,并不是对象所有属性都要参与序列化,我们可以使用JsonIgnore特性排除不需要序列化的属性,下面示例中的PasswordHash将被忽略。
public class Accounts { public string FullName { get; set; } public string EmailAddress { get; set; } [Newtonsoft.Json.JsonIgnore] public string PasswordHash { get; set; } }
Accounts account = new Accounts { FullName = "admin",EmailAddress = "1930906722@qq.com",PasswordHash = "dfsfgerhtyhsasdhjyujtgwe454811sfsg8d" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(account); Console.WriteLine(json);
执行结果:
24、序列化或反序列化时指定日期时间格式,JSON.NET中提供一个名为JsonSerializerSettings的设置对象,可通过此对象设置很多序列化和反序列化的行为,如果要设置JSON.NET序列化输出的日期时间格式,只需要指定格式化字符串即可。通过JsonSerializerSettings的DateFormatString属性指定日期时间格式:
public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public DateTime CreateDate { get; set; } }
Customer custom = new Customer { FirstName = "张三",LastName = "李四",CreateDate = DateTime.Now }; Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss",Formatting = Newtonsoft.Json.Formatting.Indented }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(custom,settings); Console.WriteLine(json);
执行结果:
Android-Gson解析JSON数据(JSON对象/JSON数组)
上一篇博客,Android-解析JSON数据(JSON对象/JSON数组),介绍了使用 org.json.JSONArray;/org.json.JSONObject; 来解析JSON数据;
Google Android 还提供来另外一种方式来解析JSON数据,那就是Gson;
Gson是非常方便的JSON解析/封装/处理等等,强大的工具类:
特点:Gson可以把JSON对象数据->转换映射为Bean对象
Gson可以把JSON数组数据->转换映射为集合
Gson可以把Bean对象->转换为JSON对象数据
Gson可以把集合->转换为JSON数组数据
...........
首先要在app/build.gradle配置文件中,导入,Gson支持包
// Gson支持包的导入
implementation ''com.google.code.gson:gson:2.6.2''
需要解析的JSON数据:
/data/data/liudeli.mynetwork01/files/pottingJSON1
{
"name":"李四",
"age":99,
"hobby":"爱好是练习截拳道"
}
/data/data/liudeli.mynetwork01/files/pottingJSONArray1
[
{
"name":"君君",
"age":89,
"sex":"男"
},
{
"name":"小君",
"age":99,
"sex":"女"
},
{
"name":"大君",
"age":88,
"sex":"男"
}
]
定义一个Bean
定义的name/age/hobby 必须要和JSON数据里面的一模一样
package liudeli.mynetwork01.entity;
/**
* 定义一个Bean
* 定义的name/age/hobby 必须要和JSON数据里面的一模一样
* {
* "name":"李四",
* "age":99,
* "hobby":"爱好是练习截拳道"
* }
*/
public class Student2 {
private String name;
private int age;
private String hobby;
public Student2(String name, int age, String hobby) {
this.name = name;
this.age = age;
this.hobby = hobby;
}
@Override
public String toString() {
return "Student{" +
"name=''" + name + ''\'''' +
", age=" + age +
", hobby=''" + hobby + ''\'''' +
''}'';
}
}
定义的name/age/sex 必须要和JSON数据里面的一模一样
package liudeli.mynetwork01.entity;
/**
* 定义一个Bean
* 定义的name/age/sex 必须要和JSON数据里面的一模一样
*
* [
* {
* "name":"君君",
* "age":89,
* "sex":"男"
* },
* {
* "name":"小君",
* "age":99,
* "sex":"女"
* },
* {
* "name":"大君",
* "age":88,
* "sex":"男"
* }
* ]
*/
public class Student {
private String name;
private int age;
private String sex;
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name=''" + name + ''\'''' +
", age=" + age +
", sex=''" + sex + ''\'''' +
''}'';
}
}
GsonAnalyzeJSONActivity.java
package liudeli.mynetwork01;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;
import liudeli.mynetwork01.entity.Student;
import liudeli.mynetwork01.entity.Student2;
public class GsonAnalyzeJSONActivity extends Activity {
private final String TAG = GsonAnalyzeJSONActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gson_analyze);
}
/**
* Gson解析JSON对象
* {
* "name":"李四",
* "age":99,
* "hobby":"爱好是练习截拳道"
* }
*/
public void gonsAnalyzeJSONObject(View view) {
String jsonData = readFile("pottingJSON1");
// Log.d(TAG, "jsonData:" + jsonData);
Gson gson = new Gson();
Student2 student2 = gson.fromJson(jsonData, Student2.class);
Log.d(TAG, "gonsAnalyzeJSONObject 解析后的结果:" + student2.toString());
}
/**
* Gson解析JSON数组
* [
* {
* "name":"君君",
* "age":89,
* "sex":"男"
* },
* {
* "name":"小君",
* "age":99,
* "sex":"女"
* },
* {
* "name":"大君",
* "age":88,
* "sex":"男"
* }
* ]
* @param view
*/
public void gonsAnalyzeJSONArray(View view) {
String jsonData = readFile("pottingJSONArray1");
// Log.d(TAG, "jsonData:" + jsonData);
Gson gson = new Gson();
/**
* TypeToken<List<需要映射的Bean对象>>(){}.getType()
*/
List<Student> list = gson.fromJson(jsonData, new TypeToken<List<Student>>(){}.getType()); // 参数二:需要指定类型,类型来决定解析的集合
for (Student student: list) {
Log.d(TAG, "gonsAnalyzeJSONArray 解析后的结果:" + student.toString());
}
}
/**
* 读取文件里面的字符串
* @param fileName
* @return
*/
private String readFile(String fileName) {
String result = null;
try {
InputStream inputStream = openFileInput(fileName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
baos.write(bytes, 0,bytes.length);
result = new String(baos.toByteArray());
baos.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
activity_gson_analyze.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gson解析JSON对象"
android:onClick="gonsAnalyzeJSONObject"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gson解析JSON数组"
android:onClick="gonsAnalyzeJSONArray"
/>
</LinearLayout>
日志的打印:
使用Gson解析,JSON对象数据:
12-23 23:00:52.108 9729-9729/liudeli.mynetwork01 D/GsonAnalyzeJSONActivity: gonsAnalyzeJSONObject 解析后的结果:Student{name=''李四'', age=99, hobby=''爱好是练习截拳道''}
使用Gson解析,JSON数组数据:
12-23 23:00:53.199 9729-9729/liudeli.mynetwork01 D/GsonAnalyzeJSONActivity: gonsAnalyzeJSONArray 解析后的结果:Student{name=''君君'', age=89, sex=''男''}
12-23 23:00:53.199 9729-9729/liudeli.mynetwork01 D/GsonAnalyzeJSONActivity: gonsAnalyzeJSONArray 解析后的结果:Student{name=''小君'', age=99, sex=''女''}
12-23 23:00:53.199 9729-9729/liudeli.mynetwork01 D/GsonAnalyzeJSONActivity: gonsAnalyzeJSONArray 解析后的结果:Student{name=''大君'', age=88, sex=''男''}
C# dynamic类型序列化和反序列化之Newtonsoft.Json,动态解析远端返回的jSON数据
一、说明
1.Newtonsoft.Json 中的Linq To Json中提供了方便的json数据查询、修改等操作。
例如:JObject,JArray
2.在JObject.FromObject()或JArray.FromObject()中也提供了对dynamic类型的支持。
二、dynamic转json字符串处理
-
using Newtonsoft.Json;
-
using Newtonsoft.Json.Linq;
1.使用JObject对象
-
dynamic obj = new JObject();
-
obj.name = "张三丰";
-
obj.age = 10;
-
obj.birthday = DateTime.Now;
-
-
Console.WriteLine(obj.ToString());
输出结果:
-
{
-
"name": "张三丰",
-
"age": 10,
-
"birthday": "2017-07-29T16:39:47.4549601+08:00"
-
}
2.使用JObject.FromObject()
-
dynamic obj = new System.Dynamic.ExpandoObject();
-
obj.name = "张三丰";
-
obj.age = 10;
-
obj.birthday = DateTime.Now;
-
-
string result = JObject.FromObject(obj).ToString();
-
Console.WriteLine(result);
输出结果:同上
三、将json字符串发序列化为dynamic类型
-
string json = @"
-
{
-
''Title'': ''Json.NET is awesome!'',
-
''Author'': {
-
''Name'': ''James Newton-King'',
-
''Twitter'': ''@JamesNK'',
-
''Picture'': ''/jamesnk.png''
-
},
-
''Date'': ''2013-01-23T19:30:00'',
-
''BodyHtml'': ''<h3>Title!</h3>\r\n<p>Content!</p>''
-
}
-
";
-
dynamic blogPost = JObject.Parse(json);
-
string title = blogPost.Title;
-
Console.WriteLine(title); //输出:Json.NET is awesome!
-
Console.WriteLine(blogPost.Date); //输出:2013/1/ 23 19:30:00
官方示例:
Querying JSON with dynamicCreate JSON with dynamic
更多:
C# Newtonsoft.Json JsonSerializerSettings配置序列化操作
C#Json序列化、反序列化之Dictionary 字典类型
C# Newtonsoft.Json之LINQ To Json实例(二)
关于Newtonsoft.Json解析json数据和如何解析json数据的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于.net 使用 Newtonsoft.Json 输出树状 json字符串、.Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程、Android-Gson解析JSON数据(JSON对象/JSON数组)、C# dynamic类型序列化和反序列化之Newtonsoft.Json,动态解析远端返回的jSON数据的相关知识,请在本站寻找。
本文标签: