当前位置:K88软件开发文章中心编程语言.NET.NET01 → 文章内容

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

减小字体 增大字体 作者:loveasp     来源:asp编程网  发布时间:2018-12-30 7:43:30

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

首先要下载Newtonsoft.Json.dll,下载地址:http://www.K88.NET/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.K88.NET"

}
]
}
给这个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字符串中的网址。如果你想弹出其他东西,自己修改一下就好了。



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