Jayrock.Json读取json数据(net)
- 格式:doc
- 大小:31.50 KB
- 文档页数:2
JQuery获取json数据$.getJSON⽅法的实例代码前台:复制代码代码如下:function SelectProject() {var a = new Array;var r = window.showModalDialog('SelProject.aspx', a, "dialogWidth=1000px; dialogHeight=600px; resizable: yes"); if (typeof (r) != 'undefined') {var arr = r.split(";");$("#hidProjectInnerID").val(arr[0]);$("#txtProjectNo").val(arr[1]);$.getJSON("../Handler/GetProjectInfor.ashx", { key: "PaymentStatement", InnerID: $("#hidProjectInnerID").val() }, function (json) {$("#labFinalCustomer").text(json.finalclient);$("#labOrderNo").text(json.orderno);var strDeviceTr = "";$.each(json.workinghours, function (i, item) {strDeviceTr += "<tr><td><lable name="infor"> " + item.description + "</lable> </td>";strDeviceTr += "<td> </td>";strDeviceTr += " <td><lable name="infor"> " + item.hoursdays + "</lable></td>";strDeviceTr += "<td> 0.8</td>";strDeviceTr += "<td><lable name="infor"> " + item.workinghour + " </lable></td>";strDeviceTr += "<td> 0.8</td>";strDeviceTr += "<td><lable name="infor"> " + item.workinghour + "</lable></td>";strDeviceTr += "<td> </td>";strDeviceTr += "</tr>";});$("#infor").append(strDeviceTr);});}}ashx复制代码代码如下:string innerid = CommonClass.Request.GetRequest<string>("InnerID", "");string key = CommonClass.Request.GetRequest<string>("key", "");string result = "";if (key == "StockOutApp" && innerid != ""){result = StockOutApp(innerid);context.Response.Write(result);}else if (key == "PaymentStatement" && innerid != ""){result = PaymentStatement(innerid);context.Response.Write(result);}#region 结算单信息public string PaymentStatement(string _innerid){try{string sql = @"select InnerID,pFinalClient,pOrderNo from se_ProjectMain where InnerID='" + _innerid + "'";DataTable dt = SqlShift.GetDataTable(sql);if (!CommonClass.DTRow.CheckDtIsEmpty(dt)){StringBuilder json = new StringBuilder();json.Append(""innerid":""+dt.Rows[0]["InnerID"].ToString()+""");json.Append(","finalclient":"" + dt.Rows[0]["pFinalClient"].ToString() + """);json.Append(","orderno":"" + dt.Rows[0]["pOrderNo"].ToString() + """);json.Append(","workinghours":" + GetWorkingHours(_innerid));return "{" + json.ToString().Trim(',') + "}";}else{return string.Empty;}}catch (Exception ex){AppLog.Write("项⽬获取异常![异常信息:" + ex.Message + "]", );return string.Empty;}}public string GetWorkingHours(string _innerid){try{string sql = @"select InnerID, wDescription,wWorkingHour,wHours_Days from se_ProjectWorkingHour where wProjectID='" + _innerid + "'";DataTable dt = SqlShift.GetDataTable(sql);if (!CommonClass.DTRow.CheckDtIsEmpty(dt)){StringBuilder json = new StringBuilder();for (int i = 0; i < dt.Rows.Count; i++){json.Append("{");json.Append(""innerid":"" + dt.Rows[0]["InnerID"].ToString() + """);json.Append(","description":"" + dt.Rows[0]["wDescription"].ToString() + """);json.Append(","workinghour":"" + dt.Rows[0]["wWorkingHour"].ToString() + """);json.Append(","hoursdays":"" + dt.Rows[0]["wHours_Days"].ToString() + """);json.Append("},");}return "[" + json.ToString().Trim(',') + "]";}else{return string.Empty;}}catch (Exception ex){AppLog.Write("项⽬获取异常![异常信息:" + ex.Message + "]", );return string.Empty;}}#endregion。
JSON数据的详细解析方法JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于Web应用程序之间的数据传输。
它由键值对组成,可以包含对象、数组、数字、字符串、布尔值和null。
下面将详细解析JSON数据的方法。
1.JSON基本结构:2.解析JSON数据的方法:(1)使用各种编程语言的内置函数:大多数编程语言都提供了内置函数来解析JSON数据。
例如,在JavaScript中,可以使用JSON.parse(方法将JSON字符串转换为JavaScript对象。
在Python中,可以使用json模块中的json.loads(函数将JSON字符串转换为Python字典或列表。
(2)手动解析:如果没有内置函数可用或想要更深入了解JSON数据的结构,可以手动解析JSON数据。
- 首先,将JSON字符串转换为支持键值对结构的数据类型,如字典(Python)或对象(JavaScript)。
-然后,通过键名或属性访问特定的值,或者通过遍历数组访问元素。
3.对象的解析:JSON对象由键值对组成,可以通过键名访问对应的值。
例如,假设有以下JSON对象:"age": 30,"city": "New York"可以通过以下方式解析该对象:(1)使用内置函数:通过JSON.parse(方法(JavaScript)或json.loads(函数(Python)将JSON字符串转换为对象,然后通过对象的属性访问值。
(2)手动解析:将JSON字符串转换为支持键值对的数据类型,如字典(Python)或对象(JavaScript),然后通过键名访问值。
4.数组的解析:例如,假设有以下JSON数组:[ "apple", "banana", "orange" ]可以通过以下方式解析该数组:(1)使用内置函数:通过JSON.parse(方法(JavaScript)或json.loads(函数(Python)将JSON字符串转换为数组,然后通过索引访问特定元素。
jquery $.getJSON 与.NET 结合用法推荐废话不多说,给出文件先:Handler.ashx<%@ WebHandler Language="C#"Class="Handler"%>using System;using System.Web;using System.Data;using System.Text;public class Handler : IHttpHandler {public void ProcessRequest (HttpContext context) {/*context.Response.ContentType = "text/plain";string data = "[{name:\"fan\",age:26},{name:\"wang \",age:25}]";//构建的json数据context.Response.Write(data);*/DataSet ds = new DataSet();DataTable dt = new DataTable();dt.Columns.Add("name", typeof(string));dt.Columns.Add("year", typeof(string));dt.Columns.Add("avg", typeof(string));DataRow tr = dt.NewRow();tr["name"] = "张三";tr["year"] = "2005-02-02";tr["avg"] = "男";dt.Rows.Add(tr);//ds.Tables.Add(dt);DataRow tr2 = dt.NewRow();tr2["name"] = "李四";tr2["year"] = "2007-02-02";tr2["avg"] = "女";dt.Rows.Add(tr2);ds.Tables.Add(dt);context.Response.Clear();context.Response.ContentEncoding = Encoding.UTF8;context.Response.ContentType = "application/json";//Response.Write("{\"success\":true,\"name\":\"张三\",\"year\":\"2009-12-12\"}");context.Response.Write(getJSON(ds));context.Response.Flush();context.Response.End();}public bool IsReusable {get{return false;}}private static string getJSON(DataSet ds)//这里调用了JSON帮助文件,jsonHelp.cs 就不放出源码了{Json.JSONHelper jsonHelp = new Json.JSONHelper();jsonHelp.success = true;//jsonHelp.totlalCount = getPrjListCount();jsonHelp.totlalCount = ds.Tables[0].Rows.Count;foreach(DataRow dr in ds.Tables[0].Rows){jsonHelp.AddItem("name", dr["name"].ToString ());jsonHelp.AddItem("avg", dr["avg"].ToString() );if(dr["year"] != DBNull.Value){jsonHelp.AddItem("year", Convert.ToD ateTime(dr["year"]).ToString("yyyy/MM/dd"));}else{jsonHelp.AddItem("year", string.Empt y);}jsonHelp.ItemOk();}string strResult = jsonHelp.ToString();return strResult;}}test.aspx<script src="js/jquery.js" type="text/javascript" language ="javascript"></script><script type="text/javascript">$(function(){$.getJSON("Handler.ashx",function(json){$.each(json.data,function(i){$('#content').ap pend("姓名:"+json.data[i].name+"----性别:"+json.data[i].avg+"----时间:"+json.data[i].year+"<br/>");});});});</script><body><form id="form1" runat="server"><div id="content"></div></form></body>把Handler.ashx文件内容放入普通aspx文件page_load方法中同样适用即$.getJSON("ssss.aspx"function(e){});。
本文由我司收集整编,推荐下载,如有疑问,请与我司联系使用jQuery AJAX 加载JSON 数据I need to print this information when clicking a button and sorting if by date, so far i have this: I have json file that looks like this, but I haven’t been able to print it on the page and still haven’t got to the sorting by date part. I am not sure if the problem is the link to the ajax version i am using or what is the problem, because i saw an example that looksjust like this on youtube and it works just fine.我需要在单击按钮时打印此信息并按日期排序,到目前为止我有这个:我有json文件看起来像这样,但我无法在页面上打印它仍然没有得到按日期排序部分。
我不确定问题是否是我正在使用的ajax 版本的链接或问题是什么,因为我在youtube 上看到了一个看起来像这样的例子,它工作得很好。
JSON:JSON:[ “users”:[ “name”:“user1”,“Endorsement”:“some comment”,“date”:“8/11/2012”“name”:“user2”,“Endorsement”:“some comment2”,“date”:“9/27/11”“name”:“user3”,“Endorsement”:“some comment3”“name”:“user4”,“Endorsement”:“some comment4”,“date”:“4/2/13”“name”:“user5”,“Endorsement”:“some comment5”“name”:“user6”,“Endorsement”:“some comment6”,“date”:“3/17/13”“name”:“user7”,“Endorsement”:“some comment7”,“date”:“5/22/13”“name”:“user8”,“Endorsement”:“some comment8”,“date”:“9/27/13” ]]HTML updated:HTML 已更新:!DOCTYPE html html lang=“en”head meta charset=“utf-8”meta name=“viewport”content=“width=device-width, initial-scale=1.0”title Contact /title link rel=“shortcut icon”href=“stridesFavicon.ico”link rel=“stylesheet”href=“css/bootstrap.css”link rel=“stylesheet”href=“css/bootstrap-responsive.css”link。
解析json的3种方法JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它易于人们阅读和编写,同时也易于机器解析和生成。
在日常的软件开发中,我们经常会遇到需要解析JSON数据的情况。
本文将介绍解析JSON的三种方法,希望能够帮助大家更好地理解和应用JSON数据。
第一种方法是使用内置的JSON对象进行解析。
在JavaScript 中,可以使用JSON对象的parse方法将JSON字符串转换为JavaScript对象,或者使用stringify方法将JavaScript对象转换为JSON字符串。
这种方法简单易用,适用于简单的JSON数据解析和生成。
第二种方法是使用第三方库进行解析。
除了内置的JSON对象,还有许多第三方库可以用来解析JSON数据,例如在Node.js中常用的库有`jsonparse`、`json5`等。
这些库通常提供了更多的功能和更灵活的选项,可以满足各种复杂的JSON数据解析需求。
第三种方法是使用JSON Schema进行解析。
JSON Schema是一种用于描述JSON数据结构的语言,可以用来验证和解析JSON数据。
通过定义JSON Schema,可以规定JSON数据的结构和约束条件,然后使用相应的工具来解析和验证JSON数据。
这种方法适用于需要对JSON数据进行严格验证和规范的场景。
总的来说,解析JSON数据有多种方法可供选择,每种方法都有其适用的场景和特点。
在实际应用中,我们可以根据具体的需求和情况选择合适的方法来解析JSON数据,以便更好地处理和利用JSON数据。
希望本文介绍的三种方法能够对大家有所帮助,让大家在日常的软件开发中更加轻松地处理JSON数据。
jqueryajax获取json并解析,获取的json是object对象格式⾸先我们使⽤的是ajax⽅式,推荐⼀个学习⽹址:这个博主写的特别好。
现在来看我们的例⼦:这⾥是没有参数的get⽅式:function tryapitest(){$.ajax({url:"/api/category/top/all",type:"get",dataType:"json",success: function(data) {console.log(data);},error: function(XMLHttpRequest, textStatus, errorThrown) {alert(XMLHttpRequest.status);alert(XMLHttpRequest.readyState);alert(textStatus);},})}控制台打印出的数据如下:可以看到,我们获取的data由三级组成:ststus,msg,data;那么接下来,我们需要获取data:Array(12)这个数据;因此在success函数⾥⾯添加如下:success: function(data) {//console.log(data);var item=data.data;console.log(item);}},此时查看console控制台的输出信息:可以看到此时已经获得Object的信息了,但是如果需要获取Object⾥⾯具体的属性,必须要将Object进⾏遍历:代码如下:success: function(data) {//console.log(data);var item=data.data;//console.log(item);for(var i=0;i<item.length;i++){console.log(item[i]);}},查看控制台的信息:此时就可以获取对应的数据和属性啦。
使⽤Ajax获取本地json数据⼀、使⽤原⽣ajax获取本地JSON⽂件中的数据1)创建json数据⽂件,⽂件名:demo.jsontext.json内的数据代码如下:{"person":{"name":"tom","age":18}}2)HTML⽂档中的代码如下:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>index</title></head><body><script>var xhr="";//声明变量容纳XMLHttpRequest对象//封装XMLHttpRequest对象创建⽅法(⽤于兼容低版本IE浏览器)function createXHR(){if(new window.XMLHttpRequest){//如果浏览器⽀持对象XMLHttpRequestxhr=new XMLHttpRequest();}else{xhr=new ActiveXObject("Microsoft.XMLH");//低版本IE使⽤ActiveXObject}}createXHR();//调⽤函数以创建XMLHttpRequest对象//使⽤XMLHttpRequest对象发送请求xhr.open("get","./demo.json",false);//创建请求xhr.send(null);//发送请求//获取返回的json数据,var personStr=xhr.responseText;//返回的数据都是字符串,不具备对象⽅法var per=JSON.parse(personStr);//使⽤JSON.parse⽅法将字符串数据转换为javascript对象console.log()//tom</script></body></html>⼆、使⽤Ajax获取本地json⽂件中的数据(注:使⽤jquery获取json中的数据,不需要再使⽤JSON.parse()将数据转为javascript对象)<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>index</title><script src="/ajax/jquery/jquery-1.8.0.js"></script></head><body><script>$(document).ready(function(){$.ajax({type: "get",//请求类型datatype: "json",//数据类型url: "./demo.json",//向哪⾥请求success: function(data){//请求成功后执⾏该函数console.log()//tom}})})</script></body></html>另、获取HTML⽂档内部的JSON数据<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>index</title></head><body><script>var jsonData='{"name": "tom","age": 18}';//创建json数据var per=JSON.parse(jsonData);//将json数据转换为javascript对象console.log()//tom</script></body></html>。
本文实例讲述了jQuery+ajax+获取Json值的方法。
分享给大家供大家参考,具体如下:代码如下:<html xmlns="/1999/xhtml"><head> <title>jQueryAjaxJson取值示例</title> <script type="text/javascript" src="Scripts/jquery-1.4.4.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#Button1").click(function () { $.ajax({ url: 'AjaxQuery.aspx', type: 'GET', dataType: 'json', timeout: 1000, cache: false, beforeSend: LoadFunction, //加载执行方法 error: erryFunction, //错误执行方法 success: succFunction //成功执行方法 }) function LoadFunction() { $("#ddd").html('加载中...'); } function erryFunction() { alert("error"); } function succFunction(tt) { $("#ddd").html(''); var json = eval(tt); //数组 $.each(json, function (index, item) { //循环获取数据 var name = json[index].Name; var age = json[index].Age; var sex = json[index].Sex; $("#ddd").html($("#ddd").html() + "<br>" + name + " - " + age + " - " + sex + "<br/>"); }); } }); }) </script></head><body> <input type="button" id="Button1" value="获取json数据" /> <span id="ddd"></span></body></html>代码如下://Ajax Post Textfunction savedata(tempid) { var tid = $('#hidtemplate').attr('value'); var desc = $("#contentdiv").html(); var num_iid = $("#num_iidArr").attr('value'); var num_iid2 = $("#num_iidArr001").attr('value'); //发布页面 var topsvalue = $("#tops").attr('value'); if (num_iid != "" && num_iid2 != "") { $.ajax({ url: 'TabBaoHandler.ashx', type: 'POST', data: 'type=3&num_iid=' + num_iid2 + '&tid=' + tid + '&desc=' + desc + '&top_session=' + topsvalue, dataType: 'text', timeout: 20000, cache: false, //async: false, //同步 beforeSend: LoadFunction, //加载执行方法 error: erryFunction, //错误执行方法 success: succFunction //成功执行方法 }) function LoadFunction() { showLoad("正在运行中..."); } function erryFunction() { $("#contentdiv").html("<p style=\"padding:5px\"><img src=\"images/error.png\" />sorry,提交失败</p>"); closeLoad(); } function succFunction(tt) { closeLoad(); $("#contentdiv").show().html(tt); } } else { alert("请选择后再操作"); }}代码如下:using System;//新增using System.Web.Script.Serialization;using System.Collections.Generic;public partial class AjaxQuery : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { List<Student> list = new List<Student>(); Student c = new Student(); = "张三"; c.Age = 23; c.Sex = "男"; list.Add(c); Student cc = new Student(); = "李四"; cc.Age = 25; cc.Sex = "男"; list.Add(cc); Student ccc = new Student(); = "李玲"; ccc.Age = 25; ccc.Sex = "女"; list.Add(ccc); Response.ContentType = "application/json"; Response.Write(new JavaScriptSerializer().Serialize(list));////这个很关键,否则error Response.End(); } } public struct Student { public string Name; public int Age; public string Sex; }}希望本文所述对大家jQuery程序设计有所帮助。
java怎么读取json格式的数据public static Person getPerson(String key,String jsonString){ Person person = new Person(); try { JSONObject jsonObject = new JSONObject(jsonString); JSONObject personObject = jsonObject.getJSONObject("person"); person.setId(personObject.getInt("id"));person.setName(personObject.getString("name"));person.setAddress(personObject.getString("address")); } catch (Exception e) { // TODO: handle exception } return person; } public static List<Person> getPersons(String key,String jsonString){ List<Person> list = new ArrayList<Person>(); try { JSONObject jsonObject = new JSONObject(jsonString); //返回json数组 JSONArray jsonArray =jsonObject.getJSONArray(key); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject2 = jsonArray.getJSONObject(i); Person person = new Person();person.setId(jsonObject2.getInt("id")); person.setName(jsonObject2.getString("name")); person.setAddress(jsonObject2.getString("address")); list.add(person); } } catch (Exception e) { // TODO: handle exception } return list; } public static List<String> getList(String key,String jsonString){ List<String> list = new ArrayList<String>(); try { JSONObject jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray(key); for (int i = 0;i < jsonArray.length(); i++) { String msg = jsonArray.getString(i); list.add(msg); } } catch (Exception e) { // TODO: handle exception } return list; } public static List<Map<String, Object>> getListMap(String key,String jsonString){ List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); try { JSONObject jsonObject = newJSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray(key); for (int i = 0;i < jsonArray.length(); i++) { JSONObject jsonObject2 = jsonArray.getJSONObject(i);Map<String, Object> map = new HashMap<String, Object>(); Iterator<String> iterator = jsonObject2.keys(); while (iterator.hasNext()) { String json_key = iterator.next(); Objectjson_value = jsonObject2.get(json_key); if (json_value == null) { json_value = ""; }map.put(json_key, json_value); } list.add(map); } } catch (Exception e) { // TODO: handle exception } return list; }。
1:首先下载Jayrock.Json.dll文件,放入bin目录中;地址:/down/Jayrock.Json.dll_356701.html
2:如下json格式:
using Jayrock.Json;
string jsonWriter =
"{'games':[{'username':'is_51315925', 'player_level':'2'},{'username':'is_61315925', 'player_level':'3'}]}";
JsonReader jsonRead = new JsonTextReader(new StringReader(jsonWriter));
JsonObject jsonObj = new JsonObject();
//将文本的jsonWriter数据转变成一个对象
jsonObj.Import(jsonRead);
//获取games内容转化成JsonArray对象:
JsonArray gameArray = jsonObj["games"] as JsonArray;
//两个数组{},循环获取每个数组中的“username”的值
foreach (JsonObject o in gameArray)
{
string c = o["username"].ToString();
}
3:如下json格式
string strJsonText = @"{"cacheCount":1,"count":"34","slice":"5, 5","list":
[1001598,1001601,1001605,1001609,1001612],"page":1,"error":200}";
JsonReader reader = new JsonTextReader(new StringReader(strJsonText));
JsonObject jsonObj = new JsonObject();
jsonObj.Import(reader);
这样,就将一个文本的JSon数据转变成一个对象,如果要获取 count 的值,则可以这样
string count = jsonObj["count"].ToString();
但是有个问题,list 是一个数组,该如何获取呢?不用急,Jayrock已经为我们准备好了,来看
using (JsonTextReader textReader = new JsonTextReader(new
StringReader(jsonObj["list"].ToString())))
{
while (textReader.Read())
{
if (!string.IsNullOrEmpty(textReader.Text))
{
Response.Write(textReader.Text);
} }
}。