Reputation: 2748
I am using Newtonsoft Json.net to try and parse some Json data from a file in my C# WinForms application, however I am running into a problem when I read in the data.
I read the data into a string and then deserialise it into my json object but the object is always null and holds no data.
My Json data/string
{
"titles": {
"Title": "Write your title here",
"SubTitle": "Write your subtitle here"
},
"signees": {
"SigneeTitle0": "Name of the first signee here",
"SigneeTitle1": "Name of the second signee here",
"SigneeTitle2": "Name of the third signee here"
}
}
Json Object
public class JsonTitles
{
public string Title { get; set; }
public string SubTitle { get; set; }
}
Code to read in json data
public void ReadFormDataFile(string fileLocation)
{
string tmp = File.ReadAllText(fileLocation);
JsonTitles titles = JsonConvert.DeserializeObject<JsonTitles>(tmp);
}
I know that the data is being read in correctly as I can see it in my tmp string when debugging.
Any help appreciated, thanks.
Upvotes: 1
Views: 3420
Reputation: 7706
You should use the class which is corresponding to the whole input string and not only to some part of it. So you can use class like below:
public class InputObject{
public TitlesClass titles {get;set;}
public SigneesClass signees {get;set;}
}
public class TitlesClass {
public string Title {get;set;}
public string SubTitle {get;set;}
}
public class SigneesClass {
public string SigneeTitle0 {get;set;}
public string SigneeTitle1 {get;set;}
public string SigneeTitle2 {get;set;}
}
public void ReadFormDataFile(string fileLocation)
{
string tmp = File.ReadAllText(fileLocation);
InputObject parsedObject = JsonConvert.DeserializeObject<InputObject>(tmp);
}
Upvotes: 4