2017-05-05 95 views
-2

我使用這個類:C#轉換類JSON文件

class message 
    { 
     public content Content { get; set; } 
     public from From { get; set; } 
     public personalizations Personalizations { get; set; } 
    } 


    public class content 
    { 
     public string type = "text/html"; 
     public string value = "html"; 
    } 

    public class from 
    { 
     public string email = "[email protected]"; 
     public string name = "example"; 

    } 
    public class personalizations 
    { 
     public List<to> tos { get; set; } 
    } 
    public class to 
    { 
     public string subject { get; set; } 
     public string email { get; set; } 
    } 

我正在序列化的類消息到:

var msg = new message() { Content = new content() { type = "text/html", value = "html" }, 
     From = new from() { email = "[email protected]", name = "example" }, 
     Personalizations = new personalizations() { tos = new List<to>() { new to(), new to() } } }; 
    var data = JsonConvert.SerializeObject(msg); 

我想要得到的數組每一位家長 的JSON輸出格式爲

{ 
    "Content": { 

    "type": "text/html", 
    "value": "html" 
    }, 
    "From": { 
    "email": "[email protected]", 
    "name": "example" 
    }, 
    "Personalizations": 
    { 
    "tos": [ 
     { 
     "subject": null, 
     "email": null 
     }, 
     { 
     "subject": null, 
     "email": null 
     } 
    ] 
    } 
} 

,但我確實希望這種格式相反:

{ 
    "content": [ 
    { 
     "type": "text/html", 
     "value": "Html" 
    } 
    ], 
    "from": { 
    "email": "", 
    "name": "" 
    }, 

    "personalizations": [ 
    { 
     "subject": "", 
     "to": [ { "email": "" }] 
    }, 
    { 
     "subject": "", 
     "to": [{ "email": "" }] 
    }, 
    { 
     "subject": "", 
     "to": [{ "email": "" }] 
    } 

    ] 

} 

我該如何設法將格式更改爲最後一個?

在此先感謝

編輯:

我想改變的格式不是值 例如:

在過去的JSON例子,我有很多個性至極的對象

容納多個JSON但在第一個我只有一個對象

+0

'空= 「」'.... – Gusman

+0

見http://stackoverflow.com/questions/23830206/json-convert-empty -string-instead-of-null – shurik

+0

@shurik你是對的......很明顯,OP知道如何從JSON構造類,以及如何將對象表示爲單個元素數組 - 重新打開並等待澄清他們完全有問題。 –

回答

0

根據你最新的評論,你想改變輸出格式。您可以通過從「到」類「個性化」類移動的資源「公共字符串主題」實現這個目標,就像這裏:

https://dotnetfiddle.net/40nBnl

你應該,順便說一下,看看C# naming conventions

0

你可以把你想要結束的JSON複製到剪貼板。然後,您可以從編輯菜單中進入Visual Studio中的任何.cs文件,您可以展開「選擇性粘貼」菜單。選擇選項 「粘貼JSON作爲班」,你會得到這樣的:!

public class Rootobject 
{ 
    public Content[] content { get; set; } 
    public From from { get; set; } 
    public Personalization[] personalizations { get; set; } 
} 

public class From 
{ 
    public string email { get; set; } 
    public string name { get; set; } 
} 

public class Content 
{ 
    public string type { get; set; } 
    public string value { get; set; } 
} 

public class Personalization 
{ 
    public string subject { get; set; } 
    public To[] to { get; set; } 
} 

public class To 
{ 
    public string email { get; set; } 
}