簡體   English   中英

C#JSON Newtonsoft轉換

[英]c# json newtonsoft conversion

我試圖從這個json創建一個序列化字符串:

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

到目前為止,我已經創建了這些類:

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; }
}

並嘗試使用此代碼來構建數據:

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);

但這似乎只會導致以下結果:

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

如何根據原始json填充所有部分?

您沒有分配其他屬性。 因此,它們的序列化值保持為空。

只需添加它們,就像您分配了reportTypeLang一樣:

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

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

並附帶說明:有一個很酷的功能,可以將JSON作為類粘貼 ,如果您不想自己寫下它們,它會自動為您生成必要的類:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM