1

I want to access data from a json file in my file directory.

I have tried using StreamReader but it does not deserialize the data.

string json = r.ReadToEnd();

WorkFlowConfiguration items = 
    JsonConvert.DeserializeObject<WorkFlowConfiguration>(json);

Debug.WriteLine(items.WorkFlowAction);
Console.WriteLine(items.WorkFlowAction);

items.WorkFlowAction.ForEach(el => Console.WriteLine(el.ToString()));
9
  • Can you see the file content in string json variable after line1 of your code snippet? Commented Sep 19, 2019 at 4:16
  • Do you get any error in this code? What error? Commented Sep 19, 2019 at 4:42
  • 3
    there is File.ReadAllText() method Commented Sep 19, 2019 at 4:48
  • What result do you get right now, and what were you expecting? Commented Sep 19, 2019 at 5:17
  • 1
    @rena thanks a lot for your cooperation. i got solved my problem. now it is working. problem was that accessing syntax. Commented Sep 23, 2019 at 6:59

2 Answers 2

2

There are two ways to get the external json file like below:

1.Model:

public class Test
{
    public string status { get; set; }
    public int code { get; set; }
    public string message { get; set; }
}

2.Json file:

  {
    "status": "succeess",
    "code": 1,
    "message": "login succeeded!"
  }

3.The first way(Use StreamReader):

using (StreamReader r = new StreamReader("C:\\test.json"))
    {
         string json = r.ReadToEnd();
         Test item =JsonConvert.DeserializeObject<Test>(json);
    }

4.The second way(Use File.ReadAllText):

var jsonString = System.IO.File.ReadAllText("C:\\test.json");
Test items =JsonConvert.DeserializeObject<Test>(jsonString);
Sign up to request clarification or add additional context in comments.

Comments

0

if you want to access from startup class

"MySettings": {  
    "DbConnection": "abc",  
    "Email": "[email protected]",  
    "SMTPPort": "5605"  
  }  


public Startup(IConfiguration configuration)
{   
     var dbConnection= configuration["MySettings:DbConnection"];
}

or if you want in your controller, you must inject IConfiguration in you constructor

public UserController(IConfiguration configuration)  
{  
   configuration = configuration["MySettings:DbConnection"]; 
}  

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.