locked
Return Json by inner object RRS feed

  • Question

  • User-284642143 posted

    I have the below C# code which reads a Json file 

    using (StreamReader r = new StreamReader(@"E:\Folder\file.json"))
                {
                    string json = r.ReadToEnd();
                    RootObject items = JsonConvert.DeserializeObject<RootObject>(json);
                    Consoles Consoles = items.devices.consoles;
    
                    return Consoles;
                }

    Under Devices (that is items.devices.consoles;) i have consoles and adaptors etc. Is there a way for me to reuse the code above so it returns the type i pass in? i.e. 

    items.devices.consoles;
    items.devices.adaptors;
    items.devices.screens;

    Ideally i would like them return to put into a List so i can bind them to a dropdown? OR is the only way to use the above code but change the return type for each one i need?

    Thursday, November 29, 2018 4:59 PM

Answers

  • User475983607 posted

    You have everything needed.  Move the main object to a global location in your code.  Then simply access the object properties.

    RootObject items
    using (StreamReader r = new StreamReader(@"E:\Folder\file.json"))
    {
    	string json = r.ReadToEnd();
    	items = JsonConvert.DeserializeObject<RootObject>(json);
    }
    Consoles Consoles = items.devices.consoles;

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 29, 2018 6:21 PM