博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Json.Net 学习笔记(一)
阅读量:4661 次
发布时间:2019-06-09

本文共 1590 字,大约阅读时间需要 5 分钟。

使用Newtonsoft.Json这是一个开源的Json.Net库。

下载地址:。当前版本为 Release 8

从下载到的源代码中获取Newtonsoft.Json.Net20.dll,添加到自己的工程中。

using Newtonsoft.Json;

定义类:

 public class Message

    {
        public string Address { get; set; }
        [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
        public object Body { get; set; }
    }
    public class SearchDetails
    {
        public string Query { get; set; }
        public string Language { get; set; }
    }

测试:

           Message message = new Message

            {
                Address = "",
                Body = new SearchDetails { Query = "Json.Net", Language = "en-us" }
            };
            string jsonMsg = JsonConvert.SerializeObject(message, Formatting.Indented);//Indented表示以缩进形式显示结果
            System.Diagnostics.Debug.Write(jsonMsg);
            Message deserialized = JsonConvert.DeserializeObject<Message>(jsonMsg);
            SearchDetails searchDetails = (SearchDetails)deserialized.Body;
            Response.Write(searchDetails.Query + "," + searchDetails.Language + "<br/>");

Debug输出结果格式:

{

  "Address": "",
  "Body": {
    "$type": "TestJsonSerialization.SearchDetails, TestJsonSerialization",
    "Query": "Json.Net",
    "Language": "en-us"
  }
}

注:1.JsonProperty标记字段或属性,用来控制它作为一个Json对象的属性序列化。

       2.TypeNameHandling 用来为Json序列化指定类型名。它有几个枚举值:

Member Description
None Do not include the .NET type name when serializing types. 
Objects Include the .NET type name when serializing into a JSON object structure. 
Arrays Include the .NET type name when serializing into a JSON array structure. 
Auto Include the .NET type name when the type of the object being serialized is not the same as its declared type. 
All Always include the .NET type name when serializing. 

转载于:https://www.cnblogs.com/aaa6818162/archive/2011/11/16/2251107.html

你可能感兴趣的文章
二次注入原理及防御
查看>>
会话记住已登录功能
查看>>
Linux内核分析——可执行程序的装载
查看>>
第一阶段冲刺3
查看>>
父类引用指向子类对象
查看>>
网页如何实现下载功能
查看>>
IT男专用表白程序
查看>>
读《大道至简》第六章感想
查看>>
ef linq 中判断实体中是否包含某集合
查看>>
章三 链表
查看>>
Solution for Concurrent number of AOS' for this application exceeds the licensed number
查看>>
CSE 3100 Systems Programming
查看>>
IntelliJ IDEA 的Project structure说明
查看>>
Java Security(JCE基本概念)
查看>>
创建 PSO
查看>>
JasperReport报表设计4
查看>>
项目活动定义 概述
查看>>
团队冲刺04
查看>>
泛型在三层中的应用
查看>>
SharePoint2010 -- 管理配置文件同步
查看>>