5

I have a list of data points, as defined below:

public class Point {
    string Rate;
    string Date;
    string Number;

    public Point(string Rate, string Date, string Number)
    {
        this.Rate = Rate;
        this.Date = Date;
        this.Number = Number;
    }
}

Then within my code I have:

List<Point> points = populatedList;
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();

string text = javaScriptSerializer.Serialize(points);

System.IO.File.WriteAllText(@"C:\Users\Public\WriteText.txt", text);

When I go to view "WriteText.txt", however, all I have is a bunch of empty brackets: {}, {}, {} ... I have also tried doing this with only one point, and then I am left with only one matching pair of brackets. I then tried serializing a string object alone and that worked fine. Why is the JavaScriptSerializer not behaving as expected?

2
  • Do you perhaps mean to serialize points and not toSerialize? Commented Jul 25, 2014 at 21:30
  • Yes, my mistake, actual code has JsonSerialization as a separate method Commented Jul 25, 2014 at 21:31

1 Answer 1

18

The access level for class members and struct members, including nested classes and structs, is private by default. - Access ModifiersMSDN

As a result of that, the serialization will not see those properties. In order for them to be serialized, they need to be marked as public. They also need to have a public getter in order for the serializer to read the property.

public string Rate { get; set; }
public string Date { get; set; }
public string Number { get; set; }
Sign up to request clarification or add additional context in comments.

5 Comments

I've only started using C# recently, I am used to Java where I've gotten used to private access modifiers and public getters / setters. It seems like C# likes public access modifiers for class variables; is there a reason for this?
@mike - It doesn't have to be like that, you could use public { get; } instead. As for design decisions for property exposure, I think that is language agnostic.
While I agree, the examples provided by the official docs of a given language definitely seem to promote some tendencies...
@mike - That is basically a result of just making a simple example. Most of those are bare bones examples and only include properties which are going to be used so they must be exposed. Moreover, any example which is shown using an ORM is going to be using public getter and setter properties in order to faciliate database persistence. If you have a specific example in mind and are wondering why there is a public property which you think should be private, feel free to link it.
The ORM comment pretty much answers it for me

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.