Home > Net >  Extract c# object from json
Extract c# object from json

Time:02-23

I have a Json and I want to get it in my c# object.

var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
_ = JsonConvert.DeserializeObject<object>(json);

Here, I get the Json in the format of:

{{
"pipeline" : {
"url" : "url1",
"idP" : 1
},
"id": 1234,
"name" : "test1",
"state" : "inprogress",
"date" : "date"
}}

Now, from this JSON, I just want the id and idP.

How can I do that? Should I create a class with all the properties?

Can I please get a sample code?

CodePudding user response:

If you just want id and idP, you don't need to create the classes and deserialize json. You can just parse it

    var jsonParsed = JObject.Parse(json);
    var id = (Int32)jsonParsed["id"]; //1234
    var idP = (Int32) jsonParsed["pipeline"]["idP"]; //1

but you have to fix your json, by removing extra pair {}. You can make it manually if it is a typo. But if it is a bug, you can use this code, before parsing

json=json.Substring(1,json.Length-2);

or for example you can create one class

 public class Pipeline
    {
        public string url { get; set; }
        public int idP { get; set; }
    }

and deserialize only one part of json

Pipeline pipeline = jsonParsed["pipeline"].ToObject<Pipeline>(); 
  • Related