How to convert/deserialize Json result with multip

2019-06-13 04:08发布

I am consuming wcf rest service which is returning json as output.

{  
"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"
}
}

How can I deserialize the same. I don't have any class for json response.

I have to read json and to display some data from json.

Thanks

标签: c# json parsing
2条回答
Viruses.
2楼-- · 2019-06-13 04:34

Here are your classes:

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; }
}

you can use JSON2Csharp.com to get generated classes for you Json in C#.

Use Newton Soft Json library to Deserialize json.

you can Deserialise using this method of library:

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 ;

In my case i was sending a web request to a Restful service and json was returning as string.

查看更多
\"骚年 ilove
3楼-- · 2019-06-13 04:34

How can I deserialize the same. I don't have any class for json response.

If you don't have classes for json string, You can deserialize to dynamic object at runtime.

Example:

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

Try it online

Output:

test12@yahoo.com

en-US

查看更多
登录 后发表回答