Sourabh Chawla
Sourabh Chawla

Reputation: 3

string object is unable to Deserialize into specific object C#

  1. Serialize data in string format
string data = "{\"VerifyOTPResult\":{\"ReturnCode\":\"200\",\"ReturnMsg\":\"Invalid OTP.\",\"Data\":{\"BrokerName\":null,\"ErrorMsg\":null,\"Id\":null,\"IsValidUser\":false,\"RoleName\":null}}}";
  1. Object Class
public class VerifyOTPResult {
  public string ReturnCode { get; set; }
  public string ReturnMsg { get; set; }
  public ValidateUserResult Data { get; set; }
}

public class ValidateUserResult {
  public string Id { get; set; }
  public bool IsValidUser { get; set; }
  public string BrokerName { get; set; }        
  public string RoleName { get; set; }
  public string ErrorMsg { get; set; }
}
  1. Using Newtonsoft.Json Assembly for DeserializeObject Try 1:
var decRes = JsonConvert.DeserializeObject<VerifyOTPResult>(content);

OUTPUT Getting null in each property except int property

Try 2:

var decRes1 = JsonConvert.DeserializeObject(content);

OUTPUT

{
    "VerifyOTPResult": {
        "ReturnCode": "200",
        "ReturnMsg": "Invalid OTP.",
        "Status": null,
        "CurrentPage": 0,
        "Data": {
            "BrokerName": null,
            "ErrorMsg": null,
            "Id": null,
            "IsValidUser": false,
            "RoleName": null
        }
    }
}

I'm unable to DeserializeObject. How to convert it into my object class?

Upvotes: 0

Views: 46

Answers (2)

Dan Wilson
Dan Wilson

Reputation: 4047

Your JSON includes VerifyOTPResult but is actually a different object with a VerifyOTPResult property. You should deserialize to some wrapper class (i.e. VerifyOTPResultResponse)

void Main()
{
    string data = "{\"VerifyOTPResult\":{\"ReturnCode\":\"200\",\"ReturnMsg\":\"Invalid OTP.\",\"Data\":{\"BrokerName\":null,\"ErrorMsg\":null,\"Id\":null,\"IsValidUser\":false,\"RoleName\":null}}}";

    var decRes = JsonConvert.DeserializeObject<VerifyOTPResultResponse>(data);

    Console.WriteLine(decRes.VerifyOTPResult.ReturnCode);
    Console.WriteLine(decRes.VerifyOTPResult.ReturnMsg);

    // Output:
    // 200
    // Invalid OTP.
}

public class VerifyOTPResultResponse
{
    public VerifyOTPResult VerifyOTPResult { get; set; }
}

public class VerifyOTPResult
{
    public string ReturnCode { get; set; }
    public string ReturnMsg { get; set; }
    public ValidateUserResult Data { get; set; }
}

public class ValidateUserResult
{
    public string Id { get; set; }
    public bool IsValidUser { get; set; }
    public string BrokerName { get; set; }
    public string RoleName { get; set; }
    public string ErrorMsg { get; set; }
}

Upvotes: 1

Aleksander Zawisza
Aleksander Zawisza

Reputation: 72

Yo might as well try serializer.Deserialize<MyObj>(str); for e.g var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);

Upvotes: 0

Related Questions