The developer-time-cheapest way would be to use C# dynamic
using Newtonsoft.Json;
Int32 GetId()
{
String jsonStr = "{ \"count\":...";
dynamic jsonBlob = JObject.Parse( jsonStr );
return jsonBlob.value[0].id;
}
Note I'm personally opposed to using dynamic
because you lose compile-time type-safety, and dynamic
is somewhat expensive for single-use operations - so you might want to process it using Json.NET's own token objects:
JObject root = JObject.Parse( jsonStr );
JToken idToken = root.Properties["value"].GetChildren().First().Properties["id"];
return idToken.ToObject<Int32>();
Finally, you could always define your own class and deserialize that way:
class Foo {
public Int32 Count { get; set; }
public FooValue[] Value { get; set; }
}
class FooValue {
public Int32 Id { get; set; }
public Guid ProjectId { get; set; }
public String Name { get; set; }
}
Foo foo = JsonConvert.Deserialize<Foo>( jsonStr );
return foo.Value[0].Id;
If the JSON format will always be consistent and you won't be processing any other JSON then you can avoid the dependency on Newtonsoft.Json (Json.NET) by using a regular-expression or even trivial string processing:
Int32 idIdx = jsonStr.IndexOf("\"id\":");
if( idIdx == -1 ) return null;
Int32 commaIdx = jsonStr.IndexOf(",", idIdx);
if( commaIdx == -1 ) return null;
return jsonStr.Substring( idIdx, commaIdx - idIdx );