0

I want to parse a json file. My first attempt with a simplified version was only partial successfull.

The simplifiend json structure looks like this

{
    "rowCount": 102,
    "data": [
        {"id": "56", "bezeichnung": "Main Center", "strasse": "foostreet"},
        {"id": "34", "bezeichnung": "Side Location", "strasse": "5th aveneue"}
    ]
}

For the outer json { "rowCount":102, "data":[]} i have a class jsonEnvelope which looks like this

public class JsonEnvelope
{
    public int RowCount { get; set; }
    public Location[] Data{ get; set; }
}

To parse the json inside the array data "data":[] i have class location which looks like this

public class Location
{
  public string id;
  public string bezeichnung;
  public string strasse;
}

My code to parse the json looks like this

string jsonString = GetJsonFromFile();
var jsonEnvelope = new JsonEnvelope();

var options = new JsonSerializerOptions();
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
jsonEnvelope = JsonSerializer.Deserialize<JsonEnvelope>(jsonString, options);
foreach (Location h in jsonEnvelope.Data)
{
    Console.WriteLine(String.Format("{0} in {1}", h.bezeichnung, h.strasse));
}
Console.WriteLine("row count = " + jsonEnvelope.RowCount);

What is working?

The line jsonEnvelope.RowCount works. The number 102 is written to the console

The foreach is not working the values of h.bezeichnung and h.strasse are not written to the console

Question

while writing my question i figured it out - i will self answer it briefly

2 Answers 2

1

The problem was that i used a field in class location instead of property. Changing the class location to this solved the issue

public class Location
{
    public string Id { get; set; }
    public string Bezeichnung { get; set; }
    public string Strasse { get; set; } 
}
Sign up to request clarification or add additional context in comments.

Comments

1

Please note that with:

  • .NET 5 or
  • System.Text.Json package version 5 added to Core3.1 projects you can use IncludeFields option:
var serializeOptions = new JsonSerializerOptions
{
    IncludeFields = true,
};

var o = JsonSerializer.Deserialize<Location>(json, serializeOptions);

1 Comment

Thanks for pointing that out. Hint "use fields only for variables that have private or protected accessibility. Data that your class exposes to client code should be provided through methods, properties, and indexers." learn.microsoft.com

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.