-1

I have the following json string. What is the best way to extract the id from it using c#?

{
    "count":1,
    "value": [ {
        "id":35,
        "projectId": "frfsdf-039a-405b-8835-5ddb00cfsdf9f107",
        "name":"Default",
        "pool":{
            "id":1,
            "scope":"8850710d-4558-4f08-8064-38000a03d209",
            "name":"Default",
            "isHosted":false,
            "poolType":"automation"
        }
    }]
}
Dai
  • 141,631
  • 28
  • 261
  • 374
doorman
  • 15,707
  • 22
  • 80
  • 145
  • 1
    See [Easiest way to parse JSON response](https://stackoverflow.com/q/34043384/3744182). – dbc Dec 31 '17 at 18:30
  • 1
    I'd check out [this thread](https://stackoverflow.com/questions/16459155/how-to-access-json-object-in-c-sharp). Should answer your question! – Kit Masaracchia Dec 31 '17 at 18:30

2 Answers2

3

Using Newtonsoft.Json:

JObejct.Parse(str)["value"].First()["id"].Value<string>()

Newtonsoft is pretty much the way to handle json in c#.

Note that you can have more then one item in the array. This code takes the first.

Ridiculous
  • 443
  • 4
  • 9
  • 1
    I would maybe first call FirstOrDefault() and then test if it is not null. First() may cause the application to fail if the collection is empty. Other than that this is a good answer – Donald Jansen Dec 31 '17 at 18:34
2

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 ); 
Dai
  • 141,631
  • 28
  • 261
  • 374