简体   繁体   中英

c# json newtonsoft conversion

Im trying to create a serialize string from this json:

report_details = {
'reportTypeLang' : 'conversations',
'reportDirections' : {
'selected' : 'inbound'
},
'times' : {
'dateRange' : 'Last5Minutes'
},
'filters' : {
'sdfDips_0' : 'in_AC10033A_AC10033A-410'
},
'dataGranularity' : {
'selected' : 'auto'
}

so far i have created these classes:

public class ReportDetails
{
    public string reportTypeLang { get; set; }
    public ReportDirections reportDirections { get; set; }
    public Times times { get; set; }
    public Filters filters { get; set; }
    public DataGranularity dataGranularity { get; set; }
}
public class ReportDirections
{
    public string selected { get; set; }
}
public class Times
{
    public string dateRange { get; set; }
}
public class Filters
{
    public string sdfDips_0 { get; set; }
}

public class DataGranularity
{
    public string selected { get; set; }
}

and tried to use this code to build the data:

ReportDetails ReportDetails = new ReportDetails();
ReportDetails.reportTypeLang = "conversations";

ReportDirections reportDirections = new ReportDirections();
reportDirections.selected = "inbound";

Times Times = new Times();
Times.dateRange = "Last5Minutes";

Filters Filters = new Filters();
Filters.sdfDips_0 = "in_AC10033A_AC10033A-410";

DataGranularity DataGranularity = new DataGranularity();
DataGranularity.selected = "auto";

string report_details = JsonConvert.SerializeObject(ReportDetails);

but this only seems to result in this object:

"{\"reportTypeLang\":\"conversations\",\"reportDirections\":null,\"times\":null,\"filters\":null,\"dataGranularity\":null}"

How do i popluate all the sections as per the original json?

You did not assign the other properties. Therfore their serialized values remain null.

Just add them, like you assigned a reportTypeLang:

ReportDirections reportDirections = new ReportDirections();
reportDirections.selected = "inbound";

ReportDetails ReportDetails = new ReportDetails();
ReportDetails.reportTypeLang = "conversations";
ReportDetails.reportDirections = reportDirections; // and so with the other props

And as a side-note: there's a cool feature paste JSON as classes which autogenerates the neccessary classes for you, if you don't wanna write them down yourself:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM