简体   繁体   中英

ISSUE READING NESTED JSON OBJECT IN C#

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>();

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM