Reputation: 75
I am getting a json result via HTTPClient request using C#, the output will look like mentioned below
{
"status": 1,
"message": "",
"data": {
"username": "abcdefghi",
"password": "oiwenkwjw"
}
}
I need to filter only "data" object using C# in a static class, I have no problem in using LINQ or any other simple method, but no need to create a separate class for it, any small help will be much appreciated, Thank you
Upvotes: 0
Views: 300
Reputation: 26315
You could also define some classes to model your JSON:
public class Data
{
public string Username { get; set; }
public string Password { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
public class RootObject
{
public int Status { get; set; }
public string Message { get; set; }
public Data Data { get; set; }
}
Then use Json.NET to deserialize the JSON and output Data
from the overridden ToString()
method:
string jsonData = @"{
'status': 1,
'message': '',
'data': {
'username': 'abcdefghi',
'password': 'oiwenkwjw'
}
}";
var deserializedJson = JsonConvert.DeserializeObject<RootObject>(jsonData);
Console.WriteLine(deserializedJson.Data);
Output:
{
"Username": "abcdefghi",
"Password": "oiwenkwjw"
}
Upvotes: 1
Reputation: 347
using Newtonsoft.Json.Linq; -- i used newtonsoft json api
string jsonData = @"{
'status': 1,
'message': '',
'data': {
'username': 'abcdefghi',
'password': 'oiwenkwjw'
}
}";
var details = JObject.Parse(jsonData);
Console.WriteLine(details["data"]);
Upvotes: 2