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
Create a simple Class representation for the Json
Then use the JsonSerializer of your choice to deserialize the Json into the class and access the property you are interested in.
In your first attempt (deserializing to
dynamic
), you’re looking for thefilenames
property in the root of the object:But it’s not in the root of the object. It’s under the
value
property:The same is true in your second attempt:
You’re missing the
value
property: