欢迎光临
我们一直在努力

C#利用Newtonsoft.Json.dll读取json字符串实例

建站超值云服务器,限时71元/月

今天介绍在winform中通过Newtonsoft.Json.dll类来处理json类,来获取json字符串类型中的值。

首先要下载Newtonsoft.Json.dll,下载地址:http://www.aspbc.com/code/showcode.asp?id=200

接下来开始了

1、打开vs2010,创建一个C# winform解决方案

2、先创建一个txt文件,用来存储json字符中,内容如下:

{
"status":"1",
"postPrice":[
{
"Productid":1,
"Productname": "手机",
"Price":25.5,
"num": 1000,
"url":"http://www.baidu.com"
},
{
"Productid":2,
"Productname": "相机",
"Price":75,
"num": 2000,
"url":"http://www.aspbc.com"
}
]
}
给这个txt命名为json.txt,放到解决方案中bin/debug文件夹下,再把Newtonsoft.Json.dll也放到这个文件夹下。

3、右击“引用”–“浏览”,找到bin/debug下的Newtonsoft.Json.dll,把这个类引用到项目中来。

4、在winform中添加一个按纽,然后双击这个按纽,进入代码编写状态,在里面输入以下C#代码

//类方式
string str = getjson();
goodsinfo g= JsonConvert.DeserializeObject<goodsinfo>(str);
for (int i = 0; i < g.postPrice.Length; i++)
{
MessageBox.Show(g.postPrice[i].url);
}

5、上面一步中有个getjson()函数,代码如下:
private string getjson()
{
StringBuilder str = new StringBuilder();
str.Append("");
string path = System.Environment.CurrentDirectory + "\\json.txt";
FileStream fs = new FileStream(path, FileMode.Open);
StreamReader m_streamReader = new StreamReader(fs);
str.Append(m_streamReader.ReadToEnd());
m_streamReader.Close();
m_streamReader.Dispose();
fs.Close();
fs.Dispose();
return str.ToString();
}

6、第四步中有个goodsinfo类,创建y方法如下:
右击解决方案名–添加–类,命名为goodsinfo.cs,在弹出的代码中,将
class goodsinfo
{
}
改成
public struct goodsinfo
{
public int status { set; get; }
public info[] postPrice { set; get; }

}
即可

7、在第六步中有个info类,创建的方法同第上,取名为info.cs,在弹出的代码中将
class info
{
}
改成
public class info
{
public int Productid { set; get; }
public string Productname { set; get; }
public decimal Price { set; get; }
public int num { set; get; }
public string url { set; get; }
}

即可

8、在这个文件的最上面加上两个引用

using Newtonsoft.Json;
using System.IO;

这样就好了,保存运行一下,看看是不是弹出了json字符串中的网址。如果你想弹出其他东西,自己修改一下就好了。

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » C#利用Newtonsoft.Json.dll读取json字符串实例
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址