Reputation: 127
I have a JSON like this
{
"Application": [
{
"Office": "London",
"LogPath": [
"\\\\server1\filepath\\"
]
},
{
"Office": "Paris",
"LogPath": [
"\\\\server2\\logpath1\\",
"\\\\server2\\logpath2\\"
]
}
],
"MailSettings": {
"MailTo": "[email protected]",
"MailSubject" : "Log Checker"
}
}
and i have create a custom class to read the json content :
public class RootObject
{
public Application Application { get; set; }
public MailSettings MailSettings { get; set; }
}
public class Application
{
public List<Offices> Offices { get; set; }
}
public class Offices
{
public string Office{ get; set; }
public IList<string> LogPath { get; set; }
}
public class MailSettings
{
public string MailTo { get; set; }
public string MailSubject { get; set; }
}
But when i try to deserialize the json with
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(json);
I return the error : the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Which is wrong with my custom class ?
Upvotes: 0
Views: 118
Reputation: 48
I tested your code.your problem is in your RootObject model. In your RootObject you have a collection of application not single application. i changed it and it wrok correctly.
Upvotes: 0
Reputation: 251172
You can generate types using json2csharp - to save hand-crafting a representation of the JSON object.
public class RootObject
{
public List<Application> Application { get; set; }
public MailSettings MailSettings { get; set; }
}
public class Application
{
public string Office { get; set; }
public List<string> LogPath { get; set; }
}
public class MailSettings
{
public string MailTo { get; set; }
public string MailSubject { get; set; }
}
Using Visual Studio "Paste JSON as Classes" gives you the equally functional, but slightly different:
public class Rootobject
{
public Application[] Application { get; set; }
public Mailsettings MailSettings { get; set; }
}
public class Mailsettings
{
public string MailTo { get; set; }
public string MailSubject { get; set; }
}
public class Application
{
public string Office { get; set; }
public string[] LogPath { get; set; }
}
Visual Studio Code users can get the same feature using the JSON as Code extension, powered by QuickType.
Upvotes: 1
Reputation: 16079
Copy your json string and use visual studio inbuild feature to create custom class for respective json.
- Goto Edit -> Special Paste -> Paste JSON as Class
This will create custom class for you. Now using Newtonsoft.Json library, you can deserialize your json.
Upvotes: 0
Reputation: 822
Your custom classes should be like it.
public class Application
{
public string Office { get; set; }
public List<string> LogPath { get; set; }
}
public class MailSettings
{
public string MailTo { get; set; }
public string MailSubject { get; set; }
}
public class RootObject
{
public List<Application> Application { get; set; }
public MailSettings MailSettings { get; set; }
}
Upvotes: 0