Search code examples
javascriptjsonnsjsonserializationgeneric-collectionsjson-deserialization

Convert JSON string to strongly typed class object in C#


I am trying to convert Json string to Strongly typed object.

Json String:

{   "ResultSet": { "Description": "ADS Loading Complet - Service request failed",
"failedReason": "ORA-06550: line 1, column 36:\nPLS-00302: component 'SP_GET_LOADING_END_DATE1' must     be declared\nORA-06550: line 1, column 7:\nPL/SQL: Statement ignored",
"isSuccess": false,
"statusCode": 400
}

Class :

public class ResultSet
{
    [DataMember]
    public bool isSuccess { get; set; }
    [DataMember]
    public string failedReason { get; set; }
    [DataMember]
    public System.Net.HttpStatusCode statusCode { get; set; }
    [DataMember]
    public string Description { get; set; }
}

I tried this but no luck.

 ResultSet resultSet = new ResultSet();
 resultSet = json_serializer.Deserialize<ResultSet>(jsonString);

Please suggest better ways of doing it..


Solution

  • as of ResultSet is an extra member in JSON you have to capsulate the ResultSet in an extra Class

    public class ResultSetJson
    {
        public ResultSet ResultSet { get; set; }
    }
    

    and

    ResultSet resultSet = json_serializer.Deserialize<ResultSetJson>(jsonString).ResultSet;
    

    or

    ResultSetJson resultSetJson = json_serializer.Deserialize<ResultSetJson>(jsonString);
    ResultSet resultSet = resultSetJson.ResultSet;