1

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.

5
  • 3
    Your object doesn’t conform to the JSON. Where’s titles? Commented Jul 30, 2018 at 14:00
  • Your JSON object does not correspond to the input JSON string. Commented Jul 30, 2018 at 14:01
  • 1
    Use Paste Json As Classes to let VS create classes for you Commented Jul 30, 2018 at 14:01
  • ARg wrong dupe target : this one better stackoverflow.com/questions/22191167/… Commented Jul 30, 2018 at 14:03
  • Great, thanks. Didn't know that Paste Json As Classes even existed! Commented Jul 30, 2018 at 14:14

1 Answer 1

4

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.