Home > Net >  Get specific value from JSON string in C#
Get specific value from JSON string in C#

Time:09-22

I have this JSON string value as defined below. I want to get he value for "code" only. I tried the solution in the internet but I am only getting a null value. Any idea on this?

 JObject json = JObject.Parse(JSON string here);
 var jsonData = json.SelectToken("serviceMessage.code");    <-- THIS RETURNS NULL

The json:

{
   "highestSeverity":"Error",
   "serviceMessage":[
      {
         "code":"3004",
         "severity":"Error",
         "reason":"Reason here."
      }
   ]
}

CodePudding user response:

As it was indicated by ADyson your serviceMessage in an array not an object. So, you have to treat it as a collection.

  1. retrieve the collection
  2. retrieve the first element from it
  3. finally, you can get the code value
JObject json = JObject.Parse(rawJson);
JArray messages = (JArray)json["serviceMessage"];
string code = messages.FirstOrDefault()?["code"]?.Value<string>()

CodePudding user response:

As serviceMessage is an array, assuming you want the first item you can simply use

var code = json["serviceMessage"][0]["code"];

Live example: https://dotnetfiddle.net/2WgkcF

CodePudding user response:

Basically you can parse it to a model and get the value for code. E.g:

public class ServiceMessage
{
     public string code { get; set; }
     public string severity { get; set; }
     public string reason { get; set; }
}

public class Root{
   public string highestSeverity { get; set; }
   public List<ServiceMessage> serviceMessage { get; set; }
}

public class AnotherClass
{
   public string MyFunction(string myJson){
       var data = JsonConvert.DeserializeObject<Root>(myJson);
       //Then you can access the value in the object
       return data.serviceMessage.FirstOrDefault().code;
   }
}
  • Related