Json简单学习

Json简单学习,第1张

JSON:JavaScript 对象表示法(JavaScript Object Notation)。

JSON 是存储和交换文本信息的语法。类似 XML。

JSON 比 XML 更小、更快,更易解析。

实例:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="json_test.aspx.cs" Inherits="Web_SoftAceTest.json.json_test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

title>Untitled Page</title>

<script type="text/javascript">

var text = '{employees:[' '{"LastName":"Getes","FirstName":"Bill"},' '{"LastName":"Yue","FirstName":"Ace"},''{"LastName":"Bush","FirstName":"George"}]}';

var obj = eval("(" text ")");

</script> <

/head>

<body>

<form id="form1" runat="server"> <

div> <p> Name:<span id="sp_name"></span><br /> Age:<span id="sp_age"></span><br /> Address:<span id="sp_address"></span><br /> Phone:<span id="sp_phone"></span> </p>

<%--<script type="text/javascript"> var JsonObject = { employees: [ { "Name": "AceYue", "Age": "22", "Address": "Guangdong Shenzheng", "Phone": "1234567" }, { "Name": "Getes", "Age": "52", "Address": "Americ", "Phone": "555-1234567" } ] };
document.getElementById("sp_name").innerHTML = JsonObject.employees[1].Name;

document.getElementById("sp_age").innerHTML = JsonObject.employees[1].Age;

document.getElementById("sp_address").innerHTML = JsonObject.employees[1].Address;

document.getElementById("sp_phone").innerHTML = JsonObject.employees[1].Phone;

</script>--%>

<p> FirstName:<span id="sp_firstname"></span><br /> LastName:<span id="sp_lastname"></span> </p>

<script type="text/javascript">

document.getElementById("sp_firstname").innerHTML = obj.employees[0].FirstName;

document.getElementById("sp_lastname").innerHTML = obj.employees[0].LastName;

</script>

</div>

form>

body>

html>

类似 XML
  • JSON 是纯文本
  • JSON 具有“自我描述性”(人类可读)
  • JSON 具有层级结构(值中存在值)
  • JSON 可通过 JavaScript 进行解析
  • JSON 数据可使用 AJAX 进行传输
相比 XML 的不同之处
  • 没有结束标签
  • 更短
  • 读写的速度更快
  • 能够使用内建的 JavaScript eval() 方法进行解析
  • 使用数组
  • 不使用保留字

JSON 值可以是:

  • 数字(整数或浮点数)
  • 字符串(在双引号中)
  • 逻辑值(true 或 false)
  • 数组(在方括号中)
  • 对象(在花括号中)
  • null

json序列化与反序列化

json的序列化需要用到DataContractJsonSerializer类,在命名空间System.Runtime.Serialization.Json;下。.NET Framework 3.5需要添加System.ServiceModel.Web引用;.NET Framework 4在System.Runtime.Serialization中。

jsonhelper类:

public class JsonHelper {

/// <summary>/// json序列号 /// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="t"></param>

/// <returns></returns>

public static string JsonSerializa<T>(T t)

{

DataContractJsonSerializer zer = new DataContractJsonSerializer(typeof(T));

MemoryStream ms = new MemoryStream();

zer.WriteObject(ms, t);

string jsonstring = Encoding.UTF8.GetString(ms.ToArray());

ms.Close();

return jsonstring;

}
/// <summary>/// json反序列化 /// </summary>

/// <typeparam name="T"></typeparam>/

// <param name="strjson"></param>

/// <returns></returns>

public static T JsonDeserializa<T>(string strjson)

{

DataContractJsonSerializer zer = new DataContractJsonSerializer(typeof(T));

MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strjson));

T obj = (T)zer.ReadObject(ms);

return obj;

}

}

Person类:

publicclass Person { publicstring Name { get; set; } publicint Age { get; set; } }

简单实现:

protectedvoid Page_Load(object sender, EventArgs e)

{

Person p = new Person();

p.Name = "Ace";

p.Age = 22;
string json = JsonHelper.JsonSerializa<Person>(p);

Response.Write(json);

}

json序列化处理日期类型的处理

JSON格式不直接支持日期和时间。DateTime值值显示为“/Date(700000 0500)/”形式的JSON字符串,其中第一个数字(在提供的示例中为 700000)是 GMT 时区中自 1970 年 1 月 1 日午夜以来按正常时间(非夏令时)经过的毫秒数。该数字可以是负数,以表示之前的时间。示例中包括“ 0500”的部分可选,它指示该时间属于Local类型,即它在反序列化时应转换为本地时区。如果没有该部分,则会将时间反序列化为Utc。

修改jsonhelper类需用到的名称空间:

using System.Runtime.Serialization.Json; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic;//List名称空间

jsonhelper类的修改:

public class JsonHelper {
/// <summary>/// json序列化 /// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="t"></param>

/// <returns></returns>

public static string JsonSerializer<T>(T t)

{

DataContractJsonSerializer zer = new DataContractJsonSerializer(typeof(T));

MemoryStream ms = new MemoryStream();

zer.WriteObject(ms, t);

string jsonstring = Encoding.UTF8.GetString(ms.ToArray());

ms.Close();
string p = @"\\/Date\((\d )\ \d \)\\/";

MatchEvaluator me = new MatchEvaluator(ConvertJsonDateToDateString)

; Regex rg = new Regex(p);

jsonstring = rg.Replace(jsonstring, me);

return jsonstring;

}
/// <summary>/// json反序列化 /// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="jsonstring"></param>

/// <returns></returns>

public static T JsonDeserializer<T>(string jsonstring)

{

string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";

MatchEvaluator me = new MatchEvaluator(ConvertDateTimeToJsonDate);

Regex rg = new Regex(p);

jsonstring = rg.Replace(jsonstring, me);

DataContractJsonSerializer zer = new DataContractJsonSerializer(typeof(T));

MemoryStream ms=new MemoryStream(Encoding.UTF8.GetBytes(jsonstring));

T obj = (T)zer.ReadObject(ms);

return obj;

}
/// <summary>/// 将Json序列化的时间由/Date(1294499956278 0800)转为字符串 /// </summary>/

// <param name="m"></param>

/// <returns></returns>

private static string ConvertJsonDateToDateString(Match m)

{

string result = string.Empty;

DateTime dt = new DateTime(1970,1,1);

dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));

dt = dt.ToLocalTime();

result = dt.ToString("yyyy-MM-dd HH:mm:ss");

return result;

}
/// <summary>/// 将时间字符串转化成json时间 /// </summary>

/// <param name="m"></param>

/// <returns></returns>

private static string ConvertDateTimeToJsonDate(Match m)

{

string result = string.Empty;

DateTime dt = DateTime.Parse(m.Groups[0].Value);

dt = dt.ToUniversalTime();

TimeSpan ts = dt - DateTime.Parse("1970-01-01");

result = string.Format("\\/Date({0} 0800)\\/",ts.TotalMilliseconds);

return result;

}

}

person类的修改:

public class Person { public string Name { get; set; } public int Age { get; set; } public DateTime LastLoginTime { get; set; } }

实例调用及对集合、字典、数组的处理:

protected void Page_Load(object sender, EventArgs e)

{

Person ps = new Person();

ps.Age = 22;

ps.Name = "Ace";

ps.LastLoginTime = DateTime.Now;
string json = JsonHelper.JsonSerializer<Person>(ps)

; Response.Write(json);
List<Person> lt = new List<Person>()

{

new Person(){Name="Ace",Age=22,LastLoginTime=DateTime.Now},

new Person(){Name="Getes",Age=55,LastLoginTime=DateTime.Now}

};

string jsonstring = JsonHelper.JsonSerializer<List<Person>>(lt);

Response.Write(jsonstring);
Dictionary<string, string> dy = new Dictionary<string, string>();

dy.Add("Name", "Ace");

dy.Add("Age","22");
string json1 = JsonHelper.JsonSerializer<Dictionary<string, string>>(dy);

Response.Write(json1);

}

用javascript处理

function ChangeDateFormat(jsondate) {

jsondate = jsondate.replace("/Date(", "").replace(")/", "");

if (jsondate.indexOf("") > 0) {

jsondate = jsondate.substring(0, jsondate.indexOf(""));

}

else if (jsondate.indexOf("-") > 0) {

jsondate = jsondate.substring(0, jsondate.indexOf("-"));

}

var date = new Date(parseInt(jsondate, 10));

var month = date.getMonth() 1 < 10 ? "0" (date.getMonth() 1) : date.getMonth() 1;

var currentDate = date.getDate() < 10 ? "0" date.getDate() : date.getDate();

return date.getFullYear() "-" month "-" currentDate;

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/2090031.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-07-22
下一篇 2022-07-22

发表评论

登录后才能评论

评论列表(0条)

保存