Home > Back-end >  How to get a specific field from response [duplicate]
How to get a specific field from response [duplicate]

Time:10-09

I use

var obj = response.Content.ReadAsStringAsync().Result; 

to get a result like

obj = {"productId":"12345"}.

How to get the value 12345 from the response result?

CodePudding user response:

If you do not want to create an object & just need to quickly get the value, use Json.NET to parse your data into a JObject & then use .GetValue :

var productId = JObject.Parse(obj).GetValue("productId").Value<string>();

Or:

var productId = JObject.Parse(obj)["productId"].ToString();

Output:

"12345"

CodePudding user response:

try this using Newtonsoft.Json or you can use .net serialiazer as well

var json = response.Content.ReadAsStringAsync().Result; 

Product product = System.Text.Json.JsonSerializer.Deserialize<Product>(json);

//or using Newtonsoft.Json
Product product= JsonConvert.DeserializeObject<Product> (json);

var productId=product.ProductId;

but you will have to create a class

public class Product 
{
 public int ProductId {get; set;}
}

shorter way

var json = response.Content.ReadAsStringAsync().Result; 

var o= JObject.Parse(json);
var productId =o["productId"];  // 12345 
  •  Tags:  
  • c#
  • Related