源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

C#实现json格式数据解析功能的方法详解

  • 时间:2022-07-25 13:17 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C#实现json格式数据解析功能的方法详解
本文实例讲述了C#实现json格式数据解析功能的方法。分享给大家供大家参考,具体如下: 来写写json的解析吧 首先添加web引用 [code]System.Web.Extensions[/code] 路径 c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Web.Extensions.dll 接下来就是两个函数了,一个是根据key来获取,一个是根据index来获取
public static bool GetValue(string json, string key, out string value)
{
  //解析失败的默认返回值
  value = "";
  JavaScriptSerializer serializer = new JavaScriptSerializer();
  try
  {
    Dictionary<string, object> obj_json = serializer.DeserializeObject(json) as Dictionary<string, object>;
    if (obj_json.ContainsKey(key))
    {
      value = serializer.Serialize(obj_json[key]);
      return true;
    }
    return false;
  }
  catch (Exception)
  {
    return false;
  }
}
public static bool GetValue(string json, int index, out string value)
{
  //解析失败的默认返回值
  value = "";
  JavaScriptSerializer serializer = new JavaScriptSerializer();
  try
  {
    object[] obj_json = serializer.DeserializeObject(json) as object[];
    if (obj_json.Length > index)
    {
      value = serializer.Serialize(obj_json[index]);
      return true;
    }
    return false;
  }
  catch (Exception)
  {
    return false;
  }
}

再上一段测试效果图吧 测试文本(用的是  [url=http://tools.jb51.net/tools/json/json_editor.htm]http://tools.jb51.net/tools/json/json_editor.htm[/url] 这个在线解析json的工具里提供的一段json格式,稍作修改 )
[url=http://tools.jb51.net/code/json]http://tools.jb51.net/code/json[/url] [b]JSON[/b][b]在线格式化工具: [/b][url=http://tools.jb51.net/code/jsonformat]http://tools.jb51.net/code/jsonformat[/url] [b]在线XML/JSON互相转换工具: [/b][url=http://tools.jb51.net/code/xmljson]http://tools.jb51.net/code/xmljson[/url] [b]json[/b][b]代码在线格式化/美化/压缩/编辑/转换工具: [/b][url=http://tools.jb51.net/code/jsoncodeformat]http://tools.jb51.net/code/jsoncodeformat[/url] [b]在线json压缩/转义工具:[/b] [url=http://tools.jb51.net/code/json_yasuo_trans]http://tools.jb51.net/code/json_yasuo_trans[/url] 更多关于C#相关内容还可查看本站专题:《[url=http://www.1sucai.cn/Special/261.htm]C#字符串操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/165.htm]C#常见控件用法教程[/url]》、《[url=http://www.1sucai.cn/Special/125.htm]WinForm控件用法总结[/url]》、《[url=http://www.1sucai.cn/Special/227.htm]C#程序设计之线程使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/266.htm]C#中XML文件操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/116.htm]C#数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/265.htm]C#数组操作技巧总结[/url]》及《[url=http://www.1sucai.cn/Special/478.htm]C#面向对象程序设计入门教程[/url]》 希望本文所述对大家C#程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部