如何将多个对象的Json结果转换/反序列化为c#类以及我们如何读取它们?

时间:2014-04-23 09:23:47

标签: c# json parsing

我正在使用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中显示一些数据。

由于

2 个答案:

答案 0 :(得分:4)

以下是您的课程:

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 生成课程。

使用Newton Soft Json library反序列化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以字符串形式返回。

答案 1 :(得分:0)

  

如何反序列化相同的内容。我没有为json回应任何课程。

如果你没有json字符串的类,你可以在运行时反序列化为动态对象。

示例:

        dynamic Jsonobject = JsonConvert.DeserializeObject<dynamic>(json);
        Console.WriteLine(Jsonobject.VerifyEmailResult.EmailQueryResult.query.email);
        Console.WriteLine(Jsonobject.VerifyEmailResult.EmailQueryResult.query["lang"]);

Try it online

输出:

  

test12@yahoo.com

     

的en-US