简体   繁体   English

C#JSON Newtonsoft转换

[英]c# json newtonsoft conversion

Im trying to create a serialize string from this json: 我试图从这个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? 如何根据原始json填充所有部分?

You did not assign the other properties. 您没有分配其他属性。 Therfore their serialized values remain null. 因此,它们的序列化值保持为空。

Just add them, like you assigned a reportTypeLang: 只需添加它们,就像您分配了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: 并附带说明:有一个很酷的功能,可以将JSON作为类粘贴 ,如果您不想自己写下它们,它会自动为您生成必要的类:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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