skip to Main Content

I have the below Json string. I need to use C# to return me "file_1.txt"

{
  "value": {
    "filenames": [
      "file_1.txt",
      "file_2.txt"
    ]
  }
}

I have tried Deserialize

        var myCustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
        var string1 = myCustomclassname.value;
        var string2 = myCustomclassname.filenames[0];

But it throws

"’Cannot perform runtime binding on a null reference

I have tried this

    JObject data = JObject.Parse(json);
    JToken filenamesToken = data.GetValue("filenames");
    List<string> filenames = JsonConvert.DeserializeObject<List<string>>(filenamesToken.ToString());

But it throws

‘Object reference not set to an instance of an object.’

2

Answers


  1. Create a simple Class representation for the Json

    public class Root
    {
        public Value value { get; set; }
    }
    
    public class Value
    {
        public List<string> filenames { get; set; }
    }
    

    Then use the JsonSerializer of your choice to deserialize the Json into the class and access the property you are interested in.

     var myLovelyRoot = JsonConvert.DeserializeObject<Root>(myLovelyJson);
     var fileName = myLovelyRoot.value.filenames.First();
    
    Login or Signup to reply.
  2. In your first attempt (deserializing to dynamic), you’re looking for the filenames property in the root of the object:

    var string2 = myCustomclassname.filenames[0];
    

    But it’s not in the root of the object. It’s under the value property:

    var string2 = myCustomclassname.value.filenames[0];
    

    The same is true in your second attempt:

    JToken filenamesToken = data.GetValue("filenames");
    

    You’re missing the value property:

    JToken valueToken = data.GetValue("value");
    JToken filenamesToken = valueToken["filenames"];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search