【winform 学习】C# 转换成JSON对象
C#里面对json的处理有2种,JavaScriptSerializer和DataContractJsonSerializer。
JavaScriptSerializer读出来就是key-value pair这种Dictionary<string, object>的东西,这个比较通用。
DataContractJsonSerializer类似于其他的Serializer,比如XMLSerializer一类的,是对象序列化/反序列化用的
第一种示例代码:
(测试发现using System.Web.Script.Serialization不能在Winform 中引用,所以JavaScriptSerializer 不用在winform中使用
那winform 下怎么解析JSON 可以参考:http://q.cnblogs.com/q/46365/ 1.Json.NET 2. 引用官方的System.Web.Extensions.dll
dll文件:可以网上下载,或者参考下面地址的方面:http://wenku.it168.com/d_000825166.shtml):
string
jsonStr =
@"{""fruits"":{""a"":""orange"",""b"":""banana"",""c"":""apple""},""name"":{""z"":""zhangsan"",""l"":""lisi""}}"
;
JavaScriptSerializer serializer =
new
JavaScriptSerializer();
Dictionary<
string
,
object
> json = serializer.DeserializeObject(jsonStr)
as
Dictionary<
string
,
object
>;
Dictionary<
string
,
object
> obj = json[
"fruits"
]
as
Dictionary<
string
,
object
>;
Console.WriteLine(obj[
"a"
]);
Console.ReadLine();
第二种:DataContractJsonSerializer很不错,(不过,要申明DataContract数据数据契约,如果参数的名字不是固定的话,用第一种更好)
[DataContract]
public
class
DanTengObj
{
[DataMember(Order = 1, Name =
"fruits"
)]
public
Fruits fruits {
get
;
set
; }
[DataMember(Order = 2, Name =
"name"
)]
public
Name name {
get
;
set
; }
[DataContract]
public
class
Fruits
{
[DataMember(Order = 1, Name =
"a"
)]
public
string
a {
get
;
set
; }
[DataMember(Order = 2, Name =
"b"
)]
public
string
b {
get
;
set
; }
[DataMember(Order = 3, Name =
"c"
)]
public
string
c {
get
;
set
; }
}
[DataContract]
public
class
Name
{
[DataMember(Order = 1, Name =
"z"
)]
public
string
z {
get
;
set
; }
[DataMember(Order = 1, Name =
"l"
)]
public
string
l {
get
;
set
; }
}
}
static
void
DanTengJsonTest()
{
string
jsonStr =
@"{""fruits"":{""a"":""orange"",""b"":""banana"",""c"":""apple""},""name"":{""z"":""zhangsan"",""l"":""lisi""}}"
;
DataContractJsonSerializer js =
new
DataContractJsonSerializer(
typeof
(DanTengObj));
using
(MemoryStream ms =
new
MemoryStream(Encoding.UTF8.GetBytes(jsonStr)))
{
DanTengObj obj = js.ReadObject(ms)
as
DanTengObj;
Console.WriteLine(obj.fruits.a);
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。