Home > Enterprise >  ISSUE READING NESTED JSON OBJECT IN C#
ISSUE READING NESTED JSON OBJECT IN C#

Time:09-09

I have an issue reading values (nationalId,surname,givenNames) from a nested json object below. Getting the error System.ArgumentNullException: Value cannot be null. (Parameter 'value') Below is my Json string and Code respectively;

{
"return": {
    "transactionStatus": {
        "transactionStatus": "Ok",
        "passwordDaysLeft": 35,
        "executionCost": 0.0
    },
    "nationalId": "123456789",
    "surname": "JOHN",
    "givenNames": "DOE"}}

C# CODE, WHERE person_jObject Holds The JSON Above

 JObject person_jObject = JObject.Parse(content5);
        person.nationalId = person_jObject["nationalId"].Value<string>();
        person.surname = person_jObject["surname"].Value<string>();
        person.givenNames = person_jObject["givenNames"].Value<string>();

CodePudding user response:

This should get you what you want:

// Usage:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
//
public class Return
{
    public TransactionStatus transactionStatus { get; set; }
    public string nationalId { get; set; }
    public string surname { get; set; }
    public string givenNames { get; set; }
}

public class Root
{
    public Return @return { get; set; }
}

public class TransactionStatus
{
    public string transactionStatus { get; set; }
    public int passwordDaysLeft { get; set; }
    public double executionCost { get; set; }
}

From https://json2csharp.com/

Of course, this won't help you if your Person object is broken.

CodePudding user response:

you have a bug in your code, you need to use root "return" property

person.nationalId = person_jObject["return"]["nationalId"].Value<string>();

but you don't need to assign each property, if you need just person, just parse your json and deserialize a person part only

    Person person=JObject.Parse(content5)["return"].ToObject<Person>();

assuming that your class person is like this

public class Person
{
      public string nationalId { get; set; }
    public string surname { get; set; }
    public string givenNames { get; set; }
   ... could be another properties
}
  • Related