Search code examples
c#jsonjson.net

JsonConvert.SerializeObject reads the structure, but not the values


I tried this piece of source code (based on NewtonSoft's JSON NuGet library), for reading a JSON file into a JSON object:

string str_File_Content = File.ReadAllText(openFileDialog1.FileName);
Rootobject existing_root = JsonConvert.DeserializeObject<Rootobject>(str_File_Content);

... and it almost worked: all JSON objects are loaded into the existing_root and in case of arrays, the number of objects seems to be correct.

But: the values of the attributes seem not to be filled in, as you can see here:

JSON file excerpt:

{
    "project": {
        "common.DESCRIPTION": "Some information",

existing_root excerpt in Watch window:

Expected    :existing_root.project.commonDESCRIPTION : Some information
Real result :existing_root.project.commonDESCRIPTION : null

What can I do in order to make JsonConvert.DeserializeObject() not only handle the structure, but also the values?


Solution

  • Your json property name contains "." symbol, which is invalid for C# property name, so you can specify correct name to use during (de)serialization with JsonPropertyAttribute:

    public class Project
    {
        [JsonProperty("common.DESCRIPTION")]
        public string commonDESCRIPTION { get; set; }
    }