質問

im trying to write a simple list to json.

no errors, executes fine but i get this output

[{},{},{}]

here is a snippet of my code. studentList is a list of objects of Student class.

    public void jsonRead()
    {
        string json = File.ReadAllText(Environment.CurrentDirectory + @"\JSON.txt");

        studentList= new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<List<Student>>(json);
    }

    public void jsonWrite()
    {

            string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(studentList);

            File.WriteAllText(Environment.CurrentDirectory + @"\JSON.txt", json);

    }

student class

class Student : IComparable
{
    private String regID {get;set;}   
    private String name {get;set;}      
    private String address {get;set;}      
    private String gender {get;set;}      
    private Double gpa {get;set;}

    public Student()
    {
        regID = null;
        name = null;
        address = null;
        gender = null;
        gpa = 0.0;
    }
    public Student(String regID, String name, String address, String gender, Double gpa)
    {
        this.regID = regID;
        this.name = name;
        this.address = address;
        this.gender = gender;
        this.gpa = gpa;
    }

    public void update(String regID, String name, String address, String gender, Double gpa)
    {
        setRegId( regID);
        setName(name);
        setAddress(address);
        setGender(gender);
        setGpa(gpa);
    }

followed by setters and getters

役に立ちましたか?

解決

found the solution. dont know if its the right approach or not, but i just made all the data members public. it worked

他のヒント

This is absolutely the right answer! Yay! But what a PAIN to find! Google doesn't let you search for strings such as "[{}]". I found that even partial protection will prevent the serializer from writing out the text. e.g. (in C#):

public String Notes {private set; get}

puts 'Notes' out of reach. This is also the solution with serializing XML, not just JSON.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top