Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSON Array to List<>?

This is my json and I need to access the values under each object in the attendance array:

{"name":" ","course":"","attendance":[{"name":"INTERNATIONAL FINANCE","type":"Theory","conducted":"55","present":"50"},{"name":"INDIAN CONSTITUTION","type":"Theory","conducted":"6","present":"6"}]}

Here is my code:

public class Att
{

    public class Attendance
    {
        public string name { get; set; }
        public string type { get; set; }
        public string conducted { get; set; }
        public string present { get; set; }
    }


    public Att(string json)
    {
        JObject jObject = JObject.Parse(json);
        JToken jUser = jObject;

        name = (string)jUser["name"];
        course = (string)jUser["course"];
        attender = jUser["attendance"].ToList<Attendance>;

    }

    public string name { get; set; }
    public string course { get; set; }
    public string email { get; set; }
    //public Array attend { get; set; }

    public List<Attendance> attender { get; set; }
}

It is the attender = jUser["attendance"].ToList<Attendance>; line that I have a problem with. It says,

Cannot convert method group ToList to non-delegate type. Did you intend to invoke this method?

How do I access those values?

like image 890
LethalMachine Avatar asked Jun 22 '14 11:06

LethalMachine


People also ask

What is the difference between {} and [] in JSON?

{} denote containers, [] denote arrays.

How do I add a list to a JSON Object?

JSONObject obj = new JSONObject(); List<String> sList = new ArrayList<String>(); sList. add("val1"); sList. add("val2"); obj. put("list", sList);

How do you convert JSON to an array?

Approach 1: First convert the JSON string to the JavaScript object using JSON. Parse() method and then take out the values of the object and push them into the array using push() method.


2 Answers

You have a typo!

attendance vs attendence

And this should work

attender = jUser["attendance"].ToObject<List<Attendance>>();

You may find the running result at DotNetFiddle

like image 150
cilerler Avatar answered Sep 18 '22 20:09

cilerler


You wanted to write:

attender = jUser["attendence"].ToList<Attendance>(); // notice the ()

About the Error: When you dont put the parantheses there, C# assumes you want to assign the function (delegate) ToList to the varaible attender, instead of invoking it and assign its return value.

like image 35
CSharpie Avatar answered Sep 18 '22 20:09

CSharpie