0

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

0

2 Answers 2

2
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"]);

Sign up to request clarification or add additional context in comments.

Comments

1

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"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.