如何将带有多个对象的Json结果转换/反序列化为c#类,以及如何读取相同的结果
本文关键字:结果 何读取 读取 对象 反序列化 转换 Json | 更新日期: 2023-09-27 17:59:25
我正在使用wcf-rest服务,该服务将返回json作为输出。
{
"VerifyEmailResult":{
"EmailQueryResult":{
"query":{
"count":1,
"created":"2014-04-23T08:38:04Z",
"email":"test12%40yahoo.com",
"lang":"en-US",
"queryType":"EmailAgeVerification",
"responseCount":0,
"results":[
]
},
"responseStatus":{
"description":"Authentication Error: The signature doesn’t match or the user'/consumer key file wasn’t found.",
"errorCode":3001,
"status":"failed"
}
},
"Message":"Error occurred",
"ResponseMessage":"Failure",
"ResultCode":"0"
}
}
如何反序列化相同的。我没有任何json响应类。
我必须读取json并显示json中的一些数据。
感谢
以下是您的类:
public class Query
{
public int count { get; set; }
public string created { get; set; }
public string email { get; set; }
public string lang { get; set; }
public string queryType { get; set; }
public int responseCount { get; set; }
public List<object> results { get; set; }
}
public class ResponseStatus
{
public string description { get; set; }
public int errorCode { get; set; }
public string status { get; set; }
}
public class EmailQueryResult
{
public Query query { get; set; }
public ResponseStatus responseStatus { get; set; }
}
public class VerifyEmailResult
{
public EmailQueryResult EmailQueryResult { get; set; }
public string Message { get; set; }
public string ResponseMessage { get; set; }
public string ResultCode { get; set; }
}
public class RootObject
{
public VerifyEmailResult VerifyEmailResult { get; set; }
}
您可以使用JSON2Csharp.com为C#中的Json获取生成的类。
使用NewtonSoft Json库对Json进行反序列化。
你可以使用以下库方法进行沙漠化:
StreamReader reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadToEnd();
var Jsonobject = JsonConvert.DeserializeObject<RootObject>(json);// pass your string json here
VerifyEmailResult result = Jsonobject.VerifyEmailResult ;
在我的例子中,我向Restful服务发送了一个web请求,json以字符串的形式返回。
如何反序列化相同的。我没有任何json响应类。
如果您没有json字符串的类,则可以在运行时反序列化为动态对象。
示例:
dynamic Jsonobject = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(Jsonobject.VerifyEmailResult.EmailQueryResult.query.email);
Console.WriteLine(Jsonobject.VerifyEmailResult.EmailQueryResult.query["lang"]);
在线试用
输出:
test12@yahoo.com
en-US